Invoke(Delegate)

后端 未结 9 1116
误落风尘
误落风尘 2020-11-22 16:33

Can anybody please explain this statement written on this link

Invoke(Delegate):

Executes the specified delegate on the thread that owns th

9条回答
  •  野性不改
    2020-11-22 16:44

    If you want to modify a control it must be done in the thread in which the control was created. This Invoke method allows you to execute methods in the associated thread (the thread that owns the control's underlying window handle).

    In below sample thread1 throws an exception because SetText1 is trying to modify textBox1.Text from another thread. But in thread2, Action in SetText2 is executed in the thread in which the TextBox was created

    private void btn_Click(object sender, EvenetArgs e)
    {
        var thread1 = new Thread(SetText1);
        var thread2 = new Thread(SetText2);
        thread1.Start();
        thread2.Start();
    }
    
    private void SetText1() 
    {
        textBox1.Text = "Test";
    }
    
    private void SetText2() 
    {
        textBox1.Invoke(new Action(() => textBox1.Text = "Test"));
    }
    

提交回复
热议问题