Difference between invoke and begininvoke: invokebegininvoke

Source: Internet
Author: User

Difference between invoke and begininvoke: invokebegininvoke

Differences between invoke and begininvoke:

I have been confused about the use and concepts of invoke and begininvoke. I have read some documents over the past two days and have a new understanding of the usage and principles of the two.

First, there are two scenarios for using invoke and begininvoke:

1. invoke and begininvoke in control.

2. invoke and begininvoke in delegrate.

The two situations are different. Here we will talk about 1st. Next, let's take a look at the official definitions of invoke and begininvoke in. NET.

Control. invoke (delegate) Method: InYesOn the thread of the basic window handle of this controlRunThe specified delegate.

Control. begininvoke (delegate parameter) Method: InCreateOn the thread where the basic handle of the control is locatedAsynchronous executionSpecify the delegate.

According to these two concepts, we generally understand that the invoke table isSynchronizationBegininvokeAsynchronous. But how does one synchronize and asynchronously? Let's do a test.

InvokeExample:

 

Private void button#click (object sender, EventArgs e) {MessageBox. show (Thread. currentThread. getHashCode (). toString () + "AAA"); invokeThread = new Thread (new ThreadStart (StartMethod); invokeThread. start (); string a = string. empty; for (int I = 0; I <3; I ++) // adjust the number of cycles to see more clearly {Thread. sleep (1000); a = a + "B";} MessageBox. show (Thread. currentThread. getHashCode (). toString () + a);} private void StartMethod () {MessageBox. show (Thread. currentThread. getHashCode (). toString () + "CCC"); button1.Invoke (new invokeDelegate (invokeMethod); MessageBox. show (Thread. currentThread. getHashCode (). toString () + "DDD");} private void invokeMethod () {// Thread. sleep (3000); MessageBox. show (Thread. currentThread. getHashCode (). toString () + "EEE ");}

 

Conclusion: after running the program, check the running sequence of the program. Values: 1AAA-> 3CCC and 1BBB-> 1EEE-> 3DDD.

Explanation: The main thread runs 1AAA, then 1BBB and 3CCC are executed simultaneously, and then invoke is used to submit the invokemethod Method to the main thread, and the Child thread waits for the main thread to execute, the invokemethod method is executed by the main thread (the invoke submitted task is executed only after the task of the main thread is completed) and 3DDD is executed.

 

BegininvokeExample:

Private void button#click (object sender, EventArgs e) {MessageBox. show (Thread. currentThread. getHashCode (). toString () + "AAA"); invokeThread = new Thread (new ThreadStart (StartMethod); invokeThread. start (); string a = string. empty; for (int I = 0; I <3; I ++) // adjust the number of cycles to see more clearly {Thread. sleep (1000); a = a + "B";} MessageBox. show (Thread. currentThread. getHashCode (). toString () + a);} private void StartMethod () {MessageBox. show (Thread. currentThread. getHashCode (). toString () + "CCC"); button1.BeginInvoke (new invokeDelegate (invokeMethod); MessageBox. show (Thread. currentThread. getHashCode (). toString () + "DDD");} private void beginInvokeMethod () {// Thread. sleep (3000); MessageBox. show (Thread. currentThread. getHashCode (). toString () + "eeeeeeeeeeeeee ");}

 

Conclusion: The execution result is 1AAA-> 1BBB and 3CCC-> 1EEE and 3DDD.

Explanation: The main thread runs 1AAA, then 1BBB and 3CCC are executed simultaneously, and then the invokemethod method is submitted to the main thread through begininvoke, then the main thread executes 1EEE (the main thread's own task execution is completed), and the Sub-thread continues to execute 3DDD.

 

Through the test and comparison of the two code segments, we will find that the delegate methods submitted by invoke and begininvoke are actually executed in the main thread, in fact, according to the definitions of invoke and begininvoke, we need to look at this problem in the Child thread. In the invoke example, we will find that the Commission method submitted by invoke can be executed before continuing to execute DDD; in the begininvoke example, we will find that after the delegate method submitted by begininvoke, the sub-thread will continue to execute DDD without waiting for the completion of the delegate method. Now let's look back at the concepts of invoke (synchronous) and begininvoke (asynchronous). In fact, what they mean is relative to the sub-thread, in fact, the call to the control is always executed by the main thread. Many of us are confused about the synchronization and Asynchronization, mainly because we chose the wrong object. In fact, sometimes it is easy to understand the concept of simply looking at it. It is mainly used when the UI is suspended for computing.

Solve the problem of accessing it from a thread that is not creating a control

 

In multi-threaded programming, we often need to update the interface display in the working thread. In multithreading, it is wrong to call interface controls directly, invoke and BeginInvoke occur to solve this problem, so that you can safely update the interface display in multiple threads.

The correct method is to encapsulate the code that involves updating the interface in the working thread as a method and call it through Invoke or BeginInvoke. The difference between the two is that one causes the worker thread to wait, while the other does not.

The so-called "one-side response operation, one-side node addition" can always be relative, so that the burden on the UI thread is not too great, because correct interface updates must always be done through the UI thread, what we need to do is to wrap most of the operations in the work thread, and put the pure interface updates into the UI thread for the purpose of reducing the burden on the UI thread.

For example, when you start a thread and want to update a TextBox in the form in the thread method ..




Using System. Threading;

// Start a thread
Thread thread = new Thread (new ThreadStart (DoWork ));
Thread. Start ();

// Thread method
Private void DoWork ()
{
This. TextBox1.Text = "I Am a text box ";
}

If you operate like above, there will be exceptions in VS2005 or 2008...

The correct method is to use Invoke \ BeginInvoke

Using System. Threading;
Namespace test
{
Public partial class Form1: Form
{
Public delegate void MyInvoke (string str1, string str2 );
Public Form1 ()
{
InitializeComponent ();


}
Public void DoWork ()
{
MyInvoke mi = new MyInvoke (UpdateForm );
This. BeginInvoke (mi, new Object [] {"I Am a text box", "haha "});
}
Public void UpdateForm (string param1, string parm2)
{
This. textBox1.Text = param1 + parm2;
}
Private void button#click (object sender, EventArgs e)
{
Thread thread = new Thread (new ThreadStart (DoWork ));
Thread. Start ();
}
}
}
Pay attention to the use of proxy! Add again later

Threads are often used during WinForm development. Sometimes, you need to access controls outside the thread in the thread, such as setting the Text attribute of textbox. If you set the program directly, the following error will be reported: It is accessed by a thread that is not creating a control. We can solve this problem in two ways. First, set the control attributes. The second is through delegate, and through delegate there are two ways, one is commonly used, the other is anonymous. The descriptions are as follows.

First, set a property value of control to false. You can add Control. checkforillegalcrossthreadcils = false in the Form_Load method. If it is set to false, it means that the call of the wrong thread is not captured. In this way, no error will be reported when the Text attribute of textbox is set in the thread. Second, it is solved through the delegate method. Common delegate methods include:

delegate void SafeSetText(string strMsg);private void SetText(string strMsg){ if(textbox1.InvokeRequired) {            SafeSetText objSet=new SafeSetText(SetText);            textbox1.Invoke(objSet,new object[]{strMsg}); } else {   textbox1.Text=strMsg; }}

You can call the SetText method when you need to set the textbox value in the thread. We can also use another way of delegation, that is, anonymous proxy, for example:

delegate void SafeSetText(string strMsg);private void SetText2(string strMsg){  SafeSetText objSet = delegate(string str)   {       textBox1.Text = str;   }   textBox1.Invoke(objSet,new object[]{strMsg});}

This can also be achieved. I personally think it is better to use proxy.

 

In C #3.0 and later versions, there is a Lamda expression, and anonymous delegation like above has a more concise way .. . NET Framework 3.5 and later versions can use the Action encapsulation method. For example, the following statement can look very concise:

 

Void ButtonOnClick (object sender, EventArgs e)

 

{

 

This. Invoke (new Action () =>

 

{

 

Button. Text = "close ";

 

}));

 

}

Related Article

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.