How to call Windows Forms controls across threads

Source: Internet
Author: User

The control in the main thread is manipulated through a child thread, but there is a problem (1) that the TextBox control is created in the main thread and is not created in the child thread, that is, it is accessed from a thread that is not creating the control. So how do you solve cross-threading calls to Windows Forms controls? You can invoke a Windows Forms control across threads by using thread delegation . Here is an example of the previous change. The code is as follows:

usingSystem;usingSystem.Collections.Generic;usingSystem.ComponentModel;usingSystem.Data;usingSystem.Drawing;usingSystem.Linq;usingSystem.Text;usingSystem.Windows.Forms;usingSystem.Threading;//add a thread's namespace namespaceppp{ Public Partial classForm1:form { PublicForm1 () {InitializeComponent (); } Thread t; //Defining thread Variables         Private voidButton1_Click (Objectsender, EventArgs e) {T=NewThread (NewThreadStart (THREADP));//Instantiating ThreadsT.start ();//Start Thread        }         Private Delegate voidSetText ();//defines a thread delegatecustom Method Threadp, which is used primarily for thread invocation. The code is as follows: Public voidthreadp () {SetText D=NewSetText (threading);//instantiate a delegate             This. Invoke (d);//executes the specified delegate on the thread that owns the underlying form handle of this controlThe custom method threading, primarily for delegate invocation. The code is as follows: Public voidThreading () {TextBox1.Text="implementing controls in the main thread of the child threads"; T.abort ();//Close Thread        }    }}

How to call Windows Forms controls across threads

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.