如何从不同的线程访问控件?

时间:2011-03-09 08:57:12

标签: c# multithreading

如何从创建它的线程以外的线程访问控件,避免跨线程错误?

以下是我的示例代码:

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

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

4 个答案:

答案 0 :(得分:12)

这有一个众所周知的小模式,它看起来像这样:

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

除了测试它之外,还有我不建议使用的快速脏修复。

Form.CheckForIllegalCrossThreadCalls = false;

答案 1 :(得分:2)

您应该检查Invoke方法。

答案 2 :(得分:1)

检查 - 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;
    }
}

答案 3 :(得分:1)

您应该使用InvokeRequired方法检查您是否在同一个线程或不同的线程上。

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

您的方法可以通过这种方式重构

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