First look at the followingCode:
Using system;
Using system. text;
Using system. Windows. forms;
Using system. Threading;
Namespace inter-thread Communication
{
Public partial class form1: Form
{
Public form1 ()
{
Initializecomponent ();
}
// 1. Create the invoke function, which is roughly as follows:
/// <Summary>
/// Delegate function to be invoked by main thread
/// </Summary>
Private void invokefun ()
{
If (maid. value <100)
{
Prgbar. value = prgbar. Value + 1;
Button1.text = prgbar. value. tostring ();
}
If (prgbar. value = 100)
{
MessageBox. Show ("finished", this. Text );
Prgbar. value = 0;
}
}
// 2. subthread entry function:
/// <Summary>
/// Thread function interface
/// </Summary>
Private void threadfun ()
{
// Create invoke method by specific function
Methodinvoker MI = new methodinvoker (this. invokefun );
For (INT I = 0; I <100; I ++)
{
This. begininvoke (MI); // Let the main thread access the control created by itself.
Thread. Sleep (100); // execute time-consuming operations on the new thread.
}
}
// 3. Begin from here
Private void button#click (Object sender, eventargs E)
{
Thread thdprocess = new thread (New threadstart (threadfun ));
Thdprocess. Start ();
}
}
}
If the sub-thread accesses the control created by the main thread without processing, the system will report an error, telling us that it cannot be called directly between threads. because different threads run in parallel in different memory spaces without interference. so how can we access the desired control in the Child thread?
In fact, as shown in the above example, it is not complicated to implement inter-thread communication. thdprocess. after start (), a new thread starts. This thread starts from threadfun. the following are the key issues:
The methodinvoker delegate is used in the code, which is described in msdn as follows: any method that declares void in the delegate executable hosting code and does not accept any parameters, you can use this delegate when calling the control's invoke method or when you need a simple delegate and do not want to define it yourself. Here it actually represents the invokefun () method.
Another important method is begininvoke (delegate), which indicates that the specified delegate is executed asynchronously on the thread where the basic handle of the control is created. It can call the delegate asynchronously and return the result immediately. You can call this method from any thread (or even the thread that owns the control handle. If the control handle does not exist, this method searches along the control's parent chain until it finds a control or form with a window handle. This asynchronous call is used to access the corresponding control of the main thread by the subthread.
Let's look back at the three simple steps: Create and start a thread-> specify the delegate method-> asynchronous call.