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

问题产生和现象:

垮线程调用控件属性,现象如下:

解决方法:

方法1

Control.CheckForIllegalCrossThreadCalls = false;

方法2

private void button1_Click(object sender, EventArgs e)
{
Thread.CurrentThread.Name
= "Form Thread";
Thread td
= new Thread(new ThreadStart(SetControlText));
td.Name
= "Customer Thread";
td.Start();
}
private void SetControlText()
{
if (this.InvokeRequired)
{
this.Invoke(new Action(SetControlText));
}
else
{
this.textBox1.Text = DateTime.Now.ToString();
}
}

通用起见,可以考虑这样做:

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Thread.CurrentThread.Name
= "Form Thread";
Thread td
= new Thread(new ThreadStart(SetControlText));
td.Name
= "Customer Thread";
td.Start();
}
private void SetControlText()
{
this.InvokeIfNeeded(delegate(string str) { this.textBox1.Text = str; }, DateTime.Now.ToString("yyMMdd"));
// or
//this.InvokeIfNeeded((str)=> this.textBox1.Text = str,DateTime.Now.ToString("yyMMdd"));
}
}
public static class ControlExtensions
{
public static void InvokeIfNeeded<T>(this Control ctl, Action<T> act, T args)
{
if (ctl.InvokeRequired)
{
ctl.Invoke(act, args);
}
else
{
act(args);
}
}
}

备注:

Control.InvokeRequired Property

Usage

Gets a value indicating whether the caller must call an invoke method when making method calls to the control because the caller is on a different thread than the one the control was created on.

Property Value

true if the control's Handle was created on a different thread than the calling thread (indicating that you must make calls to the control through an invoke method); otherwise, false.

原文地址:https://www.cnblogs.com/cnbwang/p/1923678.html