方式一(在程序初始化构造函数中加一行代码):
1 public Form1() 2 { 3 InitializeComponent(); 4 Control.CheckForIllegalCrossThreadCalls = false; //设置不捕获线程异常 5 }
方式二(推荐):
1 private void btnLoop_Click(object sender, EventArgs e) 2 { 3 Thread thread = new Thread(()=> { 4 while (true) 5 { 6 if (btnLoop.InvokeRequired) // InvokeRequired:如果是别的线程创建的控件 7 { 8 //找到创建btnLoop控件的线程,执行后面委托方法,第一个参数:委托;第二个参数:传入委托的参数列表 9 btnLoop.Invoke(new Action<string>(s=> { this.btnLoop.Text = s; }),DateTime.Now.ToString()); 10 } 11 else //自己线程创建的控件 12 { 13 this.btnLoop.Text = DateTime.Now.ToString(); 14 } 15 Console.WriteLine(DateTime.Now); 16 } 17 }); 18 thread.IsBackground = true; //设置为后台线程 19 thread.Start(); 20 }