第一種:通過Invoke()在應用程序的主線程上執行指定的委托
//新開一個線程,顯示當前時間 new Thread(o => { while (true) { Thread.Sleep(1000); Invoke((Action)delegate { this.textBox1.Text= DateTime.Now.ToString(); }); } }) { IsBackground = true }.Start();
第二種:使用類BackgroundWorker
//聲明后台工作對象 BackgroundWorker BgWork = new BackgroundWorker(); //綁定事件 private void Form1_Load(object sender, EventArgs e) { BgWork.DoWork += BgWork_Demo; BgWork.RunWorkerAsync(); } //要后台執行的函數 void BgWork_Demo(object sender, DoWorkEventArgs e) { try { Random rd = new Random(); int i=rd.Next(1,3); if (i=1) { this.Invoke((EventHandler)(delegate { this.textBox1.Text = "成功就行懷孕,大家都會恭喜你!"; })); } else this.Invoke((EventHandler)(delegate { this.textBox1.Text = "但是沒有人知道《你被搞了》多少遍才成功!"; })); } catch (Exception ex) { MessageBox.Show("程序出來點小問題..." + ex.Message, "系統提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Information); } }
第三種:使用一個Timer結合異步委托方法
Timer tm = new Timer(); private void Form_Load(object sender, EventArgs e) { tm.Interval = 1000; tm.Tick += tm_Tick; this.BeginInvoke((EventHandler)(delegate { tm.Start(); })); } void tm_Tick(object sender, EventArgs e) { if (1 == 2) { tm.Stop(); //do something... } }
今天的知識就到這里啦,學會了沒有。