当创建的线程操作界面上的控件的时候,会抛出入校异常    
  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(); }

 

相关文章:

  • 2021-06-16
  • 2021-10-03
  • 2021-07-02
  • 2021-08-10
  • 2022-01-16
  • 2021-10-25
  • 2021-11-28
  • 2021-11-27
猜你喜欢
  • 2021-12-02
  • 2021-12-18
相关资源
相似解决方案