From http://www.cnblogs.com/evlon/archive/2009/10/24/1589344.html
Developing winform using dotnetfx2.0ProgramIt is often necessary to use background threads to perform operations, and update and display the operation process data, result data, and other information to the window. Because the form thread and the worker thread are not a thread, we cannot directly set the properties of the control in the form in the work thread, but need to use control. invoke (delegate del ,...). In fact, you can use an anonymous function for simple calls.
According to the standard practice on msdn, if there is a function:
Void Writemessage ( String MSG)
{
This . Tbmsg. Text + = MSG;
}
To call a function in a working thread, you must declare a delegate first:
Public Delegate Void Writemessagehandle ( String );
Then, call the following in the thread function:
Public Void Threadproc ( Object OBJ)
{
..
This . Invoke ( New Writemessagehandle ( This . Writemessag, New Object [] { " Hello World " }));
..
}
In fact, for the following sentence: This. tbmsg. Text + = MSG; It's a big deal. In C #2.0, we can be very simple: // First declare the delegate used for 10 thousand.
Public Delegate Void Voiddelegate ();
Public Void Threadproc ( Object OBJ)
{
// This is the message to be output.
String MSG = " Hello World " ;
.
// Because it is in the work thread, we do not need to handle this. invokerequired, directly call
// Use the anonymous function directly, so that you can use the MSG local variable. Haha is simple.
This . Invoke ( New Voiddelegate ( Delegate ()
{
// This is the function to be executed.
This . Tbmsg. Text + = MSG;
// Other Code related to the form can also be called here
// Ex
// This. tbname. Text = "my name here ";
}));
.
}