【问题标题】:How to access a Control from a different Thread?如何从不同的线程访问控件?
【发布时间】:2011-03-09 08:57:12
【问题描述】:

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

这是我的示例代码:

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

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

【问题讨论】:

标签: c# multithreading


【解决方案1】:

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

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

还有一个我不推荐使用的快速脏修复,除了测试它。

Form.CheckForIllegalCrossThreadCalls = false;

【讨论】:

  • 正确答案,除了模式是众所周知的:)
  • 那我们换个词吧,因为我不是指未知的意思,只是“小图案”部分。
  • Form.CheckForIllegalCrossThreadCalls = false; - 这正是我所需要的。我只有几个可以从后台线程设置的计数器。逻辑上没有什么重要的,只是显示在屏幕上。我不在乎比赛条件...谢谢!
【解决方案2】:

您应该检查Invoke 方法。

【讨论】:

    【解决方案3】:

    您应该使用 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";       
    }
    

    【讨论】:

      【解决方案4】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多