Reference: Invoke and BeginInvoke understanding
Windows GUI programs based on message loop mechanism
public static void Main (string[] args)
{
Form f = new form ();
Application.Run (f);
}
. NET Form program encapsulates the while loop, which is initiated by the Application.Run method. If you manipulate a control on a form from another thread, it will compete with the main thread, causing unpredictable results or even deadlocks. So Windows GUI programming has a rule that you can manipulate the control's data only by creating a thread of the control .
In. NET, the control class implements the ISynchronizeInvoke interface, which provides the invoke and BeginInvoke methods to provide a mechanism for other threads to update GUI interface controls. The invocation is marshaled to the thread on which the control is executing through a delegate.
Either the Invoke or BeginInvoke method requires a delegate object as a parameter. The delegate is similar to the address of the callback function, so the caller can then marshal the function address that needs to be called to the interface thread. In these methods, if you include code that changes the state of the control, it is the interface thread that eventually executes the method, which avoids the competitive conditions and avoids unforeseen problems. If other threads directly manipulate the control that the interface thread belongs to, then there will be a race condition, causing unpredictable results.
Using invoke to complete marshaling of a delegate method is a synchronous method. This means that the Invoke method does not return until the method of the invoke Marshal is executed, and the caller thread is blocked.
Marshaling a delegate method using the BeginInvoke method is an asynchronous method. That is, the method returns immediately after marshaling, does not wait for the execution of the delegate method to end, and the caller thread will not be blocked. But callers can also use the EndInvoke method or other similar WaitHandle mechanisms to wait for the completion of an asynchronous operation. But in the internal implementation, both invoke and BeginInvoke use the PostMessage method, which avoids the problem of SendMessage. The synchronous blocking of the Invoke method is done by the WaitHandle mechanism.
The InvokeRequired property is used when programming to determine whether an object needs to be marshaled using Invoke or BeginInvoke when it accesses a UI control. You can update it directly if you don't need it. This property returns False when the caller object and the UI object belong to one thread.
Private voidButton1_Click (Objectsender, EventArgs e) { if( This. Button1. invokerequired) { This. button1. BeginInvoke (NewEventHandler (button1_click),New Object[] {sender, E}); } Else { This. button1. Text ="Hello"; } }
Invoke and BeginInvoke