简体   繁体   English

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

[英]How to access a Control from a different Thread?

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";
}

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;

您应该检查Invoke方法。

Check - How to: Make Thread-Safe Calls to Windows Forms Controls 检查 - 如何:对Windows窗体控件进行线程安全调用

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

You should check with InvokeRequired method to see if you are on the same thread or a different thread. 您应该使用InvokeRequired方法检查您是否在同一个线程或不同的线程上。

MSDN Reference: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx MSDN参考: 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";       
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM