问题产生和现象:
垮线程调用控件属性,现象如下:
解决方法:
方法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.