【WinForm】线程间操作无效:子线程无法访问主线程的控件

  • Post author:
  • Post category:其他


现象

有时候,我们需要加载一些比较耗时的操作通常会在线程中加载,而在线程中涉及到UI控件,如下面的写法,就会报错:

线程间操作无效: 从不是创建控件“textBox1”的线程访问它。

Thread td = new Thread(() =>
{
    textBox1.Text = "123";
});
td.Start();

解决方法

1.不捕获对错误线程的调用

 public FrmTest()
 {
     InitializeComponent();
 
     CheckForIllegalCrossThreadCalls = false;
 }

这种属于非线程安全方式,一般不适用这种

2.线程安全方式:Invoke


(可行)

private void SetText(string text)
{
    if (textBox1.InvokeRequired)
    {
        Action<string> action = new Action<string>(SetText);
        Invoke(action, new object[] { text });
    }
    else
    {
        textBox1.Text = text;
    }
}
Thread td = new Thread(() =>
{
    SetText("123");
});
td.Start();

3.线程安全方式:BackgroundWorker

BackgroundWorker backgroundWorker1 = new BackgroundWorker();
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
 
backgroundWorker1.RunWorkerAsync();
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
    textBox1.Text = "123";
}