transferred from: http://blog.3snews.net/html/30/34530-27563.html
In multithreaded programming, we often have to update the interface display in the worker thread, and the method of invoking the interface control directly in multi-threading is the wrong way, and invoke and BeginInvoke are to solve this problem, which makes you display in a secure update interface in multi-thread.
The correct approach is to encapsulate the code that involves the update interface in a worker thread as a method, called by Invoke or BeginInvoke, and the difference is that one causes the worker to wait, while the other does not.
The so-called "side response operation, one side add node" can always be relative, so the UI thread burden is not too large, because the correct interface is always to be updated through the UI thread to do, we have to do is to take the majority of operations in the worker thread, and will be the pure interface updates into the UI thread to do, This also achieves the purpose of easing the burden on the UI thread.
Give a simple example of how you would like to update a textbox in a form when you start a thread, in a method of threading.
1 usingSystem.Threading;2 3 //Start a thread4Thread thread=NewThread (NewThreadStart (DoWork)); 5 thread. Start (); 6 7 //Threading Methods8 Private voidDoWork ()9 { Ten This. textbox1.text="I am a text box"; One}
If you act like above, there will be anomalies in VS2005 or 2008 ...
The right thing to do is to use Invoke\begininvoke
1 usingSystem.Threading;2 namespaceTest3 {4 Public Partial classForm1:form5 {6 Public Delegate voidMyinvoke (stringSTR1,stringstr2);7 PublicForm1 ()8 {9 InitializeComponent ();Ten One A } - Public voidDoWork () - { theMyinvoke mi =NewMyinvoke (updateform); - This. BeginInvoke (MI,NewObject[] {"I am a text box","haha"}); - } - Public voidUpdateForm (stringPARAM1,stringparm2) + { - This. TextBox1.Text = param1+Parm2; + } A Private voidButton1_Click (Objectsender, EventArgs e) at { -Thread thread =NewThread (NewThreadStart (DoWork)); - thread. Start (); - } - } -}
Use of Invoke in C # (GO)