通常,我們會通過線程的構(gòu)造函數(shù)先創(chuàng)建線程再使用線程。而實(shí)際上,.NET中有些類提供的方法,其內(nèi)部就是使用多線程處理的。一些封裝了多線程、異步處理方法的類都符合了"事件驅(qū)動(dòng)異步模式(event-based asynchronous pattern)"。以System.ComponentModel下的BackgroundWorker類來說,該類就符合這種模式。
BackgroundWorker類屬性:WorkerSupportsCancellation:設(shè)置為true表示允許取消WorkerReportPRogress:設(shè)置為true表示可顯示進(jìn)度
BackgroundWorker類事件:DoWork:后臺線程要做的事ProgressChanged:進(jìn)度觸發(fā)事件RunWorkerCompleted:當(dāng)進(jìn)度結(jié)束、拋出異常、或取消執(zhí)行時(shí)觸發(fā)
舉例,在Windows窗體應(yīng)用程序中使用BackgroundWorker類。
→新建一個(gè)Windows窗體應(yīng)用程序,界面包括2個(gè)button,1個(gè)label,1個(gè)progressbar,1個(gè)BackgournWorker控件。
→設(shè)置BackgournWorker控件的WorkerSupportsCancellation屬性和WorkerReportProgress為true。
→后臺代碼為:
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e){int sum = 0;for (int i = 1; i <=100; i++){Thread.Sleep(1000);sum = sum + 1;backgroundWorker1.ReportProgress(i);//如果取消計(jì)算if (backgroundWorker1.CancellationPending){e.Cancel = true;backgroundWorker1.ReportProgress(0);return;}e.Result = sum;}}private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e){//把BackgroundWorker的進(jìn)程體現(xiàn)到ProgressBar上progressBar1.Value = e.ProgressPercentage;//把BackgroundWorker的進(jìn)程體現(xiàn)到label上label1.Text = e.ProgressPercentage + "%";}private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e){if (e.Cancelled) //可能以取消的方式結(jié)束{label1.Text = "計(jì)算被取消";}else if (e.Error != null)//可能以拋出異常的方式結(jié)束{label1.Text = e.Error.Message;
新聞熱點(diǎn)
疑難解答
圖片精選