How to access a Control from a different Thread?

孤街醉人 提交于 2021-02-07 08:22:58

问题


How can I access a control from a thread other than the thread it was created on, avoiding the cross-thread error?

Here is my sample code for this:

private void Form1_Load(object sender, EventArgs e)
{
    Thread t = new Thread(foo);
    t.Start();
}

private  void foo()
{
    this.Text = "Test";
}

回答1:


There's a well known little pattern for this and it looks like this:

public void SetText(string text) 
{
    if (this.InvokeRequired) 
    {
        this.Invoke(new Action<string>(SetText), text);
    }
    else 
    { 
        this.Text = text;
    }
}

And there's also the quick dirty fix which I don't recommend using other than to test it.

Form.CheckForIllegalCrossThreadCalls = false;



回答2:


You should check for the Invoke method.




回答3:


You should check with InvokeRequired method to see if you are on the same thread or a different thread.

MSDN Reference: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx

Your method can be refactored this way

private void foo() {
    if (this.InvokeRequired)
        this.Invoke(new MethodInvoker(this.foo));
   else
        this.Text = "Test";       
}



回答4:


Check - How to: Make Thread-Safe Calls to Windows Forms Controls

private  void foo()
{
    if (this.InvokeRequired)
    {   
        this.Invoke(() => this.Text = text);
    }
    else
    {
        this.Text = text;
    }
}


来源:https://stackoverflow.com/questions/5243333/how-to-access-a-control-from-a-different-thread

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!