Control. invoke and control. begininvoke

Source: Internet
Author: User

1. Background
When multithreading is used in Windows form, besides the control creation thread (that is, the main thread ),Do not call control members in any other thread (except for a few cases). That is to say, the control belongs to the thread that creates it and cannot be accessed from other threads. This applies to all controls derived from system. Windows. Forms. Control (so it can be said that almost all controls), including the form control itself.We can easily draw a conclusion like this,The child control of the control must be created by the control creation thread.For example, a button on a form is created by a form creation thread. Therefore, all controls in a window are actually in the same thread. In actual programming, most software practices allow the same thread to take charge of all controls. This is what we call the UI thread (the main thread ).

Due to the above restrictions, we may feel inconvenient. Indeed, when we use a newly created thread to execute some time-consuming operations, how can I know the operation progress and report it to users through the UI? There are many solutions! For example, users who are familiar with multi-thread programming will soon think that we adopt some low-level synchronization methods, and the worker thread will save the state to a synchronization object so that the UI thread can polling) this object can be fed back to the user. However, this is quite troublesome. In fact, you don't need to do this,The control class (and its derived class) object has a very special invoke method, which is one of the few members that are not subject to thread restrictions.. We mentioned earlier that we should never call a member of a control not created in this thread in any other thread, but also say "only a few exceptions ", this invoke method is one of the most common cases-the invoke method can be called from any thread.

2. introduction to invoke and begininvoke
the parameters of the invoke method are simple, one delegate and one parameter table (optional ), the main function of the invoke method is to help you call the method specified by the delegate on the UI thread (that is, the thread that creates the control. The invoke method first checks whether the calling thread (that is, the current thread) is a UI thread. If yes, it directly executes the method pointed to by the delegate. If not, it switches to the UI thread, then execute the delegate pointing method. Regardless of whether the current thread is a UI thread, invoke is blocked until the execution of the method pointed to by the delegate is completed, and then the call thread is switched back (if needed) to return. Note: when using the invoke method, the UI thread cannot be in the blocking state. The following msdn description of the invoke method:
"the control has four methods that can be safely called from any thread: invoke, begininvoke, endinvoke, and creategraphics. For all other method calls, use one of the Call (invoke) Methods to block calls to the control thread.
the delegate can be an eventhandler instance. In this case, the sender parameter will include this control, and the event parameter will include eventargs. Empty. The delegate can also be a methodinvoker instance or any other delegate that uses the void parameter list. Calling eventhandler or methodinvoker delegation is faster than calling other types of delegation ."
Let's Talk About begininvoke, which is undoubtedly the asynchronous version of invoke (invoke is synchronized ), the begininvoke method always uses the UI thread. Compared with invoke, it is a little more troublesome to use begininvoke, but in that sentence, Asynchronization is better than synchronization, although it is more complicated. For example, a deadlock may occur in the synchronous method: when the worker thread synchronously calls the methods in the UI thread through invoke, what if the UI thread is waiting for the worker thread to do something? Therefore, the asynchronous method should be used whenever possible.
The following is an example to illustrate the differences between invoke and begininvoke:

Namespace controlinvoke_begininvoke
{
Public partial class form1: Form
{
Private thread mythread;
Private delegate void displaymethod (string content );
Private delegate void begininvokedelegate ();
String strcontent = string. empty;
Public form1 ()
{
Initializecomponent ();
}

Private void btnstart_click (Object sender, eventargs E)
{
If (mythread! = NULL & mythread. isalive)
{
This. btnstart. Text = "stop ";
Mythread. Abort ();
}
Else
{
This.txt main. Text = string. empty;
String strcontent = string. empty;
This. btnstart. Text = "start ";
This. mythread = new thread (New threadstart (getcontent ));
This. mythread. Start ();
}
}

Private void getcontent ()
{
This. Invoke (New displaymethod (refresh_displaycontent), "Hello World ");
MessageBox. Show ("begininvoke ");
}
Private void refresh_displaycontent (string content)
{
Thread. Sleep (5000 );
Lock (this. strcontent)
{
This. strcontent + = content + "\ r \ n ";
}
This.txt main. Text = This. strcontent;
This.txt main. Refresh ();
}
}
}

the preceding Code shows" Hello World "on the screen, and then a dialog box is displayed. If you use this. begininvoke
private void getcontent ()
{
This. begininvoke (New displaymethod (refresh_displaycontent), "Hello World");
MessageBox. show ("begininvoke");
}
the result is the opposite. Because begininvoke is an asynchronous operation, that is, the execution of the refresh_displaycontent method is asynchronous to the mythread thread.

this article from the csdn blog, reprinted please indicate the source: http://blog.csdn.net/chenlu1982/archive/2008/02/18/2102692.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.