C # Cross-thread call controls

Source: Internet
Author: User

C # Cross-thread call controls
An invalid inter-thread operation interface contains a button and a label. clicking a button will start a thread to update the Label value. Copy the code private void button#click (object sender, EventArgs e) {Thread thread1 = new Thread (new ParameterizedThreadStart (UpdateLabel); thread1.Start ("Update Label");} private void UpdateLabel (object str) {this. label1.Text = str. toString ();} after the code is copied and run, the program reports the error "cross-thread operation is invalid. It is never accessed by the thread that created" label1 "." This is because. NET prohibits cross-thread calls to controls. Otherwise, anyone can operate on the controls, which may eventually cause errors. The following describes several methods to call controls across threads. The first method is to prohibit the compiler from checking cross-thread access. This is the simplest method. It is equivalent to not checking the conflicts between threads and allowing various threads to be messed up casually, finally, it is hard to predict the value of the Lable1 Control (this method is not recommended) public Form1 () {InitializeComponent (); // Add this row of Control. checkforillegalcrossthreadcils = false;} Method 2: Use delegate and invoke to call the control's invoke method from other threads to control the control, for example, copy the code private void button2_Click (object sender, EventArgs e) {Thread thread1 = new Thread (new ParameterizedThreadStart (UpdateLabel2) ); Thread1.Start ("Update Label");} private void UpdateLabel2 (object str) {if (label2.InvokeRequired) {// when the InvokeRequired attribute value of a control is true, this indicates that a thread other than the one that creates it wants to access its Action <string> actionDelegate = (x) =>{ this. label2.Text = x. toString () ;}; // or // Action <string> actionDelegate = delegate (string txt) {this. label2.Text = txt;}; this. label2.Invoke (actionDelegate, str);} else {this. label2.Text = str. toString ();} The third method to copy the code: Use delegate and BeginInvoke to control the control from other threads as long as the above this. in label2.Invoke (actionDelegate, str);, you can change the Invoke method to the BeginInvoke method. The difference between the Invoke method and the BeginInvoke method is that the Invoke method is synchronous and will wait for the worker thread to complete, the BeginInvoke method is asynchronous. It starts another thread to complete the working thread. Method 4: Use the BackgroundWorker component (this method is recommended. NET controls used to execute multi-threaded tasks, which allow programmers to execute some operations on a separate thread. Time-consuming operations (such as downloads and database transactions ). Simple copy code private void button4_Click (object sender, EventArgs e) {using (BackgroundWorker bw = new BackgroundWorker () {bw. runWorkerCompleted + = new RunWorkerCompletedEventHandler (bw_RunWorkerCompleted); bw. doWork + = new DoWorkEventHandler (bw_DoWork); bw. runWorkerAsync ("Tank") ;}} void bw_DoWork (object sender, DoWorkEventArgs e) {// here is the background thread, is completed on another Thread // here is the real working Thread // here some time-consuming and complex operations can be done on the Thread. sleep (5000); e. result = e. argument + "Work thread completed";} void bw_RunWorkerCompleted (object sender, RunWorkerCompletedEventArgs e) {// The background thread is completed and the main thread is returned, therefore, you can directly use the UI control this. label4.Text = e. result. toString ();}

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.