当创建的线程操作界面上的控件的时候,会抛出入校异常
Cross-thread operation not valid: Control 'tbNumb' accessed from a thread other than the thread it was created on.
虽然可以通过这样来解决:TextBox.CheckForIllegalCrossThreadCalls = false;
但是不推荐这样做,微软推荐的做法如下:
//定义一个委托用于将值设置到文本框中
delegate void SetTextToControl_del(int n);
SetTextToControl_del delTextToControl = null;
private void btnStart_Click(object sender, EventArgs e)
{
//将委托指向方法SetValueToControl
delTextToControl = SetValueToControl;
//新建一个线程来执行数数
Thread t = new Thread(new ThreadStart(CountNumb));
t.IsBackground = true;
t.Start();
}
private void CountNumb()
{
for (int i = 0; i < 50000; i++)
{
tbNumb.Invoke(delTextToControl, i); //重点在这里
}
}
/// <summary>
/// 将传递过来的值存放到文本框中
/// </summary>
/// <param name="n"></param>
private void SetValueToControl(int n)
{
tbNumb.Text = n.ToString();
}