Home > Article > Backend Development > Self-study C#02 from 0--child thread accesses main thread (UI thread) control
If you use multithreading to improve the performance of a Windows Forms application, you must ensure that controls are called in a thread-safe manner.
Accessing Windows Forms controls is not inherently thread-safe. If you have two or more threads manipulating a control's state, you may force the control into an inconsistent state. Other thread-related bugs may occur, such as race conditions and deadlocks. Be sure to access controls in a thread-safe manner.
1. Problems often encountered by beginners
It is unsafe to call a control from a thread that has never used the Invoke method to create the control. Below is an example of a non-thread-safe call. An InvalidOperationException message will be thrown during runtime, with the error "The control control name is accessed from a thread that did not create the control."
// This event handler creates a thread that calls a // Windows Forms control in an unsafe way.private void setTextUnsafeBtn_Click( object sender, EventArgs e) { this.demoThread = new Thread(new ThreadStart(this.ThreadProcUnsafe)); this.demoThread.Start(); }// This method is executed on the worker thread and makes// an unsafe call on the TextBox control.private void ThreadProcUnsafe() { this.textBox1.Text = "This text was set unsafely."; }
2. Solution
If you need to make thread-safe calls to Windows Forms controls.
①Query the InvokeRequired property of the control.
②If InvokeRequired returns true, use the delegate of the actual calling control to call Invoke.
③If InvokeRequired returns false, please call the control directly.
Here are divided into synchronous execution delegation and asynchronous execution delegation.
In the following code example, thread-safe invocation 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 a SetTextCallback instance and passes it to the form's Invoke method. This causes the SetText method to be called on the thread that created the TextBox control, and the Text property to be set directly in the context of that thread.
// This event handler creates a thread that calls a // Windows Forms control in a thread-safe way. private void setTextSafeBtn_Click( object sender, EventArgs e) { this.demoThread = new Thread(new ThreadStart(this.ThreadProcSafe)); this.demoThread.Start(); }// This method is executed on the worker thread and makes // a thread-safe call on the TextBox control. private void ThreadProcSafe() { this.SetText("This text was set safely."); }// This delegate enables asynchronous calls for setting // the text property on a TextBox control.delegate void SetTextCallback(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 // SetTextCallback and calls itself asynchronously using the// Invoke method. // // If the calling thread is the same as the thread that 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 are different, it returns true. //this.textBox1.InvokeRequired will be 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 component
The preferred way to implement multi-threading in an application is to use the BackgroundWorker component. The BackgroundWorker component uses an event-driven model for multi-threaded 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 call controls from ProgressChanged and RunWorkerCompleted event handlers.
①Create a method to do the work you want to do in the background thread. Do not call controls created from the main thread in this method.
②Create a method to report the background work results after the background work ends. Controls created by the main thread can be called in this method.
③Bind the method created in step 1 to the BackgroundWorker event in the DoWork instance, and bind 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 call the form's TextBox control. The TextBox control's Text property is set directly in the RunWorkerCompleted event handler.
// This BackgroundWorker is used to demonstrate the // preferred way of performing asynchronous operations.private BackgroundWorker backgroundWorker1; // This event handler starts the form's // BackgroundWorker by calling RunWorkerAsync. // // The Text property of the TextBox 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, so the call is thread-safe. // // BackgroundWorker is the preferred way to perform asynchronous // operations.private void backgroundWorker1_RunWorkerCompleted( object sender, RunWorkerCompletedEventArgs e) { this.textBox1.Text = "This text was set safely by BackgroundWorker."; }
You can also report the progress of background tasks by using the ProgressChanged event. For an example that includes this event, see BackgroundWorker.
The above is the content of self-study C#02 from 0--child thread accessing the main thread (UI thread) control. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!