方式一(在程序初始化構造函數中加一行代碼):函數
1 public Form1() 2 { 3 InitializeComponent(); 4 Control.CheckForIllegalCrossThreadCalls = false; //設置不捕獲線程異常 5 }
方式二(推薦):oop
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 }