Invoke solved using controls between multiple threads access error

Invoke solved using controls between multiple threads access error

There on a WinForm interface of a button (button1) and a text box (textBox1), create a new thread in the button1 click event handler, and expect to change the value textBox1 in the new thread, error-prone code is as follows :

//  button click event handler Private void  button1_Click ( Object  SENDER, EventArgs E) { // create a new thread     the Thread processorThread  = null ;     processorThread  = new new  the Thread ( new new  ThreadStart (Done));     processorThread.IsBackground  = to true ;     processorThread.SetApartmentState ( ApartmentState.STA);     processorThread.Start (); } //  update value textBox1 Private void  the Done () {     textBox1.Text  = " www.mzwu.com "
 

    

 
 
 





 

  ;
}
 

Click on the button to run the program error, suggesting: invalid operation between threads: Controls are not created to access it from "textBox1" thread. Below we use Invoke to solve this problem:

//  button click event handler Private void  button1_Click ( Object  SENDER, EventArgs E) { // create a new thread     the Thread processorThread  = null ;     processorThread  = new new  the Thread ( new new  ThreadStart (Done));     processorThread.IsBackground  = to true ;     processorThread.SetApartmentState ( ApartmentState.STA);     processorThread.Start (); } //  define delegates the delegate void  WriteInvoke ( String  MSG); Private void  the Write ( String
 

    

 
 
 





 

   msg)
{
    textBox1.Text 
=  msg;
}

//  更新textBox1值
private   void  Done()
{
    
this .Invoke( new  WriteInvoke(Write),  new   object [] {  " www.mzwu.com "  });
}

 

update completed!

To summarize: in the current thread does not allow direct calls in other threads instantiated object, because this operation is not thread-safe, the compiler is prohibited. But we often want to achieve this purpose, such as creating a secondary thread, WebClient object is created in a secondary thread, used to send information and then received feedback information to an object in the main thread. Then we can use the method delegates to reach the main step is to call the object's original illegal sentence written in a separate update functions, define a function delegate class and series update function is instantiated, and finally call the Invoke method in place need to be updated to achieve their goals.

Reproduced in: https: //www.cnblogs.com/mashang/archive/2009/08/01/1536706.html

Guess you like

Origin blog.csdn.net/weixin_33860147/article/details/94160862