Invoke usage in C # (rpm)

invoke and begininvoke difference

Begininvoke been to invoke and use the concepts and chaotic, two days saw some information, and the usage of these two principles have some new knowledge and understanding.

 At first said that invoke and use begininvoke there are two cases:

  1. control of the invoke, begininvoke.

  2. delegrate in invoke, begininvoke.  

  Both situations are different, we are here to talk about the first kind. Below we in .NET and invoke begininvoke official definition of the terms under.

  control.invoke (parameters delegate) methods: have on the thread underlying window handle for this control to perform the specified delegate.

  control.begininvoke (parameters delegate): In the creation on the thread that the control's underlying handle asynchronous execution of the specified delegate.

  According to our general understanding of these two concepts invoke tables are synchronized , begininvoke represent asynchronous . But how to synchronous and asynchronous it? We do a test.

invoke examples:

 

Copy the code
private void button1_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++) //调整循环次数,看的会更清楚  { 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"); } 
Copy the code

 

Conclusion: We run, run sequence facie program, 1AAA-> 3CCC and 1BBB-> 1EEE -> 3DDD. 

Explanation: The main thread running 1AAA, then 1BBB and child thread 3CCC executed simultaneously, and then submit invokemethod method to the main thread through invoke, then the child thread waits for the main thread execution until the main thread will invokemethod method execution is completed must wait for the main thread (during task execution is completed, the mission will go to invoke submitted), the last sub-thread execution 3DDD.

 

begininvoke example:

Copy the code
private void button1_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++) //调整循环次数,看的会更清楚  { 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() + "EEEEEEEEEEEE"); }
Copy the code

 

Conclusion: We see the results after the operation performed: 1AAA-> 1BBB and 3CCC-> 1EEE and 3DDD.

Explanation: The main thread running 1AAA, then 1BBB and child thread 3CCC executed simultaneously, and then submit invokemethod method to the main thread through begininvoke, then the main thread execution 1EEE (the main thread their task execution is completed), while the child threads to continue 3DDD.

 

By comparing the two test this code, we will find that in fact invoke delegate methods and begininvoke submitted are executed in the main thread, in fact, according to my definition we invoke and begininvoke to this problem in the sub-thread of view, invoke the example we find that the delegate methods invoke submitted execution is complete, before proceeding to the DDD; after begininvoke example we find that the delegate methods begininvoke submitted, tell the child thread continues DDD, without waiting for the completion of the delegate method . So now we think back to invoke (synchronous) concepts and begininvoke (asynchronous), in fact they mean by terms relative to the child thread, in fact, to call the control is always performed by the main thread. Many of us confuse the synchronous and asynchronous, mainly because we have the wrong reference. In fact, sometimes just look at the concept is easy to understand wrong.

It was never created to solve the access control thread

 

In multi-threaded programming, we often have to work thread to update the screen display, and method call interface controls directly in multiple threads is the wrong approach, Invoke and BeginInvoke is to solve this problem occurs, so that you are more than thread safe interface to update the display.

The correct approach is to work thread involves updating interface code packaged as a method, by Invoke or BeginInvoke to call, resulting in a difference between the two is the worker thread to wait, while the other does not.

The so-called "side response actions, add side node" can only ever be relative, not to make too much of the burden on the UI thread only, because the interface is always right to do the update via the UI thread, we need to do things in the worker thread swept most of the operations, and will be updated into pure interface UI thread to do so will achieve the aim to reduce the burden on the UI thread.

Here is a simple example illustrates the case of using methods, such as you start a thread, a TextBox want to update the form in the method of the thread .. 



the System.Threading a using; 

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

// thread method 
Private void DoWork () 

this.TextBox1.Text = "I am a text box "; 


If you like the above operation, in 2008 in VS2005 or abnormal ... there will be 

the right approach is to use the Invoke \ BeginInvoke

a using the System.Threading;
namespace the Test
{
public partial class Form1: Form
{
public delegate void MyInvoke (str1 String, String str2);
public the Form1 ()
{
the InitializeComponent ();


}
public void the DoWork ()
{
MyInvoke = mi The new new MyInvoke (UpdateForm);
this.BeginInvoke(mi, new Object[] {"我是文本框","haha"});
}
public void UpdateForm(string param1,string parm2)
{
this.textBox1.Text = param1+parm2;
}
private void button1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(new ThreadStart(DoWork));
thread.Start();
}
}
}
注意代理的使用!
 

Supplementary again later

 In WinForm development process often used thread, sometimes also often require access control outside the thread in the thread, such as: set the Text property of the textbox and so on. If the setup program will certainly direct quote: Instead of creating access it from the control of the thread, the exception. Usually we can use two methods to solve. First, by setting the properties of control. Second, through the delegate, delegate also through two ways, one is the common way, while another is anonymous. It will be described below, respectively.  

First, by setting a property value is false, we can add a control Form_Load method:. Control.CheckForIllegalCrossThreadCalls = false; solved. Set to false indicates that the call does not capture the wrong thread. So in a thread when the Text property of the textbox will no longer set the error. Second, be solved by the method delegate. General delegate methods such as:

Copy the code
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; } }
Copy the code

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

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

This is also achieved. Personally I think it is better use of the agent.

 

With Lamda expression in C # 3.0 and later versions, such as the above anonymous delegates have a more concise wording. .NET Framework 3.5 or later versions with more Action packaging method. For example, the following wording may seem very simple:

 

void ButtonOnClick(object sender,EventArgs e)

 

{

 

    this.Invoke(new Action(()=>

 

    {

 

        button.Text = "OFF";

 

    }));

 

}

 https://www.cnblogs.com/lsgsanxiao/p/5523282.html

Guess you like

Origin www.cnblogs.com/xihong2014/p/11005355.html