Use the invoke method to solve the problem of cross-thread access

In C #, cross-thread direct access to the control is prohibited. InvokeRequired is created to solve this problem. When the InvokeRequired property value of a control is true, it means that a thread other than the one that created it wants to access it.
Gets a value indicating whether the caller must call the Invoke method when making a method call to the control because the caller is in a thread other than the thread where the control was created.
If you call the control method from another thread, you must use an Invoke method of the control to marshal the call to the appropriate thread

When "button2" is clicked, the label value is changed by another thread btn2, but the btn2 thread is executed by the invoke method, at this time, no error will be reported, even if the thread is called multiple times in the click event of button2 There is an error, when the button is clicked, the system knows that it is a cross-thread call, and the invoke method (delegation) is used to execute the method, and the problem is solved without error;
refer to the blog post:
https://blog.csdn.net/qq_39217004/article/details / 105439971

 if (this.InvokeRequired)
 {
      this.Invoke(new dTest(test));
 }

public Form1()
{
    InitializeComponent();
}
private Thread btn1;
private Thread btn2;


// 模拟一个实际应用
// 对label1赋值后立马检查他的值,如果已经被改过则抛出异常 
void test()
{
    try
    {
        string strText = Guid.NewGuid().ToString();//随机生成一串字符
        this.label1.Text = strText;//改变label.Text的值
        if (this.label1.Text != strText)
        {
            MessageBox.Show("label1的值意外改变", "错误提示");
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message, "跨线程访问错误提示");
    }
}

// 使用invoke方法 
public delegate void dTest();
void invokeThread()
{
    for (int i = 0; i < 102; i++)
    {
        if (this.InvokeRequired)
        {
            this.Invoke(new dTest(test));
        }
        else
        {
            test();
        }
        Thread.Sleep(10);
    }
}
// 通过invoke方法,在主线程排队,lable1的值在test函数体内永远是线程安全的. 
private void button2_Click(object sender, EventArgs e)
{
    btn2 = new Thread(new ThreadStart(invokeThread));
    btn2.Name = "通过invoke方法";
    btn2.Start();
    btn2 = new Thread(new ThreadStart(invokeThread));
    btn2.Name = "通过invoke方法";
    btn2.Start();
} 
Published 18 original articles · praised 0 · visits 233

Guess you like

Origin blog.csdn.net/qq_39217004/article/details/105439971