From 0 self-taught c#02--child threads access the main thread (UI thread) control

Source: Internet
Author: User
If you use multithreading to improve the performance of your Windows forms applications, you must ensure that the controls are invoked in a thread-safe manner.

Accessing Windows forms controls is not inherently thread-safe. If there are two or more two threads manipulating the state of the control, it may force the control to be in an inconsistent state. Other thread-related bugs, such as race conditions and deadlocks, may occur. Be sure to access the control in a thread-safe manner.

1. Frequently encountered problems for beginners

It is not safe to call a control from a thread that has never used the Invoke method to create a control. The following is an example of a non-thread-safe invocation. The runtime raises a InvalidOperationException message that "the control control name is accessed from a thread that did not create the control."

This event handler creates a thread the calls A//Windows Forms control in an unsafe way.private void settextunsafebt N_click (    object sender,     EventArgs e) {    this.demothread =         new Thread (new ThreadStart (this). Threadprocunsafe));    This.demoThread.Start ();} This method was executed on the worker thread and makes//a unsafe call on the TextBox control.private void THREADPROCU Nsafe () {    This.textBox1.Text = "This Text is set unsafely.";}


2. Workaround

If you want to make a thread-safe call to a Windows forms control.

① the InvokeRequired property of the query control.

② If InvokeRequired returns True, invoke invoke with the delegate that actually invokes the control.

③ if InvokeRequired returns false, call the control directly.

This is done by synchronously executing the delegate and executing the delegate asynchronously.

In the following code example, a thread-safe call is implemented in the Threadprocsafe method, which is executed by a background thread. If the TextBox control's invokerequired returns True, the Threadprocsafe method creates an Settextcallback instance and passes it to the form's Invoke method. This causes the TextBox method to be called on the thread that created the SetText control, and the Text property is set directly in the thread context.

This event handler creates a thread the calls A//Windows Forms control in a thread-safe way.private void Settextsafe Btn_click (object sender, EventArgs e) {this.demothread = new Thread (new ThreadStart (this).    Threadprocsafe)); This.demoThread.Start ();} This method was executed on the worker thread and makes//a Thread-safe call on the TextBox control.private void threadp Rocsafe () {this. SetText ("This text is set safely."); This delegate enables asynchronous calls for setting//the Text property on a TextBox control.delegate void Settextcall Back (string text); This method demonstrates a pattern for making thread-safe//calls on a Windows Forms control. If The calling thread is different from the thread that//created the TextBox control, this method creates a//Settex Tcallback and calls itself asynchronously using the//Invoke method.////If The calling thread is the same as the thread T Hat created//The TextBox control, the Text property is set directly.  private void SetText (string text) {//invokerequired required compares the thread ID of the//calling thread to the    Thread ID of the creating thread.    If These threads is different, it returns true. This.textBox1.InvokeRequired is replaced by//this.    InvokeRequired, if want to set many controls '//attribute or text. if (this.textBox1.InvokeRequired)//or this.        invokerequired {Settextcallback d = new Settextcallback (SetText); This.    Invoke (d, new object[] {text});    } else {this.textBox1.Text = Text; }}

3.BackgroundWorker components

The preferred way to implement multithreading in an application is to use the BackgroundWorker component. The BackgroundWorker component uses the event-driven model for multithreaded processing. The background thread runs your DoWork event handler, and the thread that created your control runs the ProgressChanged and runworkercompleted event handlers. You can invoke the control from the ProgressChanged and runworkercompleted event handlers.

① creates a way to do the work that you want to do in a background thread. Do not call the control created by the main thread in this method.

② creates a way to report background work results after the background work ends. In this method, the control created by the main thread can be called.

③ binds the method created in step 1 to the BackgroundWorker event in the DoWork instance, and binds the method created in step 2 to the RunWorkerCompleted event of the same instance.

④ to start a background thread, call the BackgroundWorker method of the RunWorkerAsync instance.

In the following code example, the DoWork event handler uses Sleep to simulate work that takes some time. It does not invoke the form's TextBox control. The TextBox control's Text property is set directly in the RunWorkerCompleted event handler.

//this backgroundworker are used to demonstrate the//preferred the-a-to performing Nchronous operations.private BackgroundWorker BackgroundWorker1; This event handler starts the form's//BackgroundWorker by calling runworkerasync.////the Text property of the Textbo X control is set//when the BackgroundWorker raises the runworkercompleted//event.private void settextbackgroundworkerbtn _click (object sender, EventArgs e) {This.backgroundWorker1.RunWorkerAsync ();} This event handler sets the Text property of the textbox//control. It is called on the thread that created the//TextBox control and so the call is thread-safe.////BackgroundWorker is the PR     Eferred to perform asynchronous//operations.private void backgroundworker1_runworkercompleted (object sender, Runworkercompletedeventargs e) {this.textBox1.Text = "This Text is set safely by BackgroundWorker.";} 

You can also report the progress of a background task by using the ProgressChanged event. For an example that contains this event, see BackgroundWorker.

These are the contents of the main thread (UI thread) control accessed from 0 self-taught c#02--threads, and more about topic.alibabacloud.com (www.php.cn)!

  • Related Article

    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.