該例子爲使用BackgroundWorker在TextBox文本中產生一個10000之內而且能被5整除的數(1秒產生一個)dom
操做界面能夠啓動線程,也能夠中止線程,界面設計如圖:spa
先貼代碼,有註釋的地方就不解釋了。線程
先引入命名空間:using System.Threading; using System.Net; 設計
整個Form1窗體代碼以下:orm
namespace BackgroundWorkerExample { public partial class Form1 : Form { public Form1() { InitializeComponent(); backgroundWorker1.WorkerReportsProgress = true; backgroundWorker1.WorkerSupportsCancellation = true; btn_Stop.Enabled = false; } private void btn_Start_Click(object sender, EventArgs e) { txt_Text.Text = "開始產生10000之內的隨機數……\n\n"; btn_Start.Enabled = false; btn_Stop.Enabled = true; //在後臺線程開始操做 backgroundWorker1.RunWorkerAsync(); } private void btn_Stop_Click(object sender, EventArgs e) { backgroundWorker1.CancelAsync(); btn_Stop.Enabled = false; btn_Start.Enabled = true; } private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { //不要直接使用組件實例名稱(backgroundWorker1),由於有多個BackgroundWorker時, //直接使用會產生耦合問題,應該經過下面的轉換使用它 BackgroundWorker worker = sender as BackgroundWorker; //下面的內容至關於線程要處理的內容。//注意:不要在此事件中和界面控件打交道 Random r = new Random(); int numCount = 0; while (worker.CancellationPending == false) { int num = r.Next(0, 10000); if (num % 5 == 0) { numCount++; worker.ReportProgress(0, num); Thread.Sleep(1000); } } e.Result = numCount; } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { int num = (int)e.UserState; txt_Text.Text += num + " "; } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Error == null) txt_Text.Text += "\n\n操做中止,共生產" + e.Result + "個能被5整除的隨機數"; else txt_Text.Text += "\n操做過程當中產生錯誤:" + e.Error; } } }
該例子在 Backgroundworker 組件的輔助線程上隨機產生整數,輔助線程運行DoWork事件處理程序,當產生能被5整除的整數時,使用ProgressChanged事件把整數顯示到窗體上。程序執行到 RunWorkerAsync 方法時,將啓動後臺線程。 在Dowork事件中,若是應用程序沒有取消後臺操做,將不停的產生隨機整數,而後判斷該整數可否被5整除,若是能被5整除,執行work.ReportProgress方法來觸發 ProgressChanged 事件,在 ProgressChanged 事件中與界面長鬚打交道,把生產的隨機整數顯示到窗體上。blog
界面編譯後運行如圖:事件