Use invoke to solve control access errors between multiple threads
From http://doudou232102.blog.163.com/blog/static/92981066200952782429613/
On a winform interface, there is a button (button1) and a text box (textbox1). Create a New thread in the click event handler of button1, you are expected to change the textbox1 value in the new thread. The error-prone code is as follows:
// Click the event handler button
Private void button#click (Object sender, eventargs E)
{
// Create a new thread
Thread processorthread = NULL;
Processorthread = new thread (New threadstart (done ));
Processorthread. isbackground = true;
Processorthread. setapartmentstate (apartmentstate. Sta );
Processorthread. Start ();
}
// Update the textbox1 Value
Private void done ()
{
Textbox1.text = "www.mzwu.com ";
}
An error occurred while clicking the button for running the program. The prompt is: The Inter-thread operation is invalid: access from a thread that is not creating the control "textbox1. Next we use invoke to solve this problem:
// Click the event handler button
Private void button#click (Object sender, eventargs E)
{
// Create a new thread
Thread processorthread = NULL;
Processorthread = new thread (New threadstart (done ));
Processorthread. isbackground = true;
Processorthread. setapartmentstate (apartmentstate. Sta );
Processorthread. Start ();
}
// Define the delegate
Delegate void writeinvoke (string MSG );
Private void write (string MSG)
{
Textbox1.text = MSG;
}
// Update the textbox1 Value
Private void done ()
{
This. Invoke (New writeinvoke (write), new object [] {"www.mzwu.com "});
}
Update successful!
To sum up, objects instantiated in other threads cannot be called directly in the current thread, because such operations are not thread-safe and the compiler prohibits them. However, we often want to achieve this goal. For example, we want to create an auxiliary thread, create a WebClient object in the auxiliary thread to send information, and then feed the received information to an object in the main thread. In this case, we can use the delegate method. The main step is to write the statements that used to call objects illegally into the UPDATE function separately, define a function delegate class, And concatenate the UPDATE function for instantiation, finally, you can call the invoke method where you want to update it.