在我們的程序中,經(jīng)常會有一些耗時較長的運算,為了保證用戶體驗,不引起界面不響應,我們一般會采用多線程操作,讓耗時操作在后臺完成,完成后再進行處理或給出提示,在運行中,也會時時去刷新界面上的進度條等顯示,必要時還要控制后臺線程中斷當前操作。
以前,類似的應用會比較麻煩,需要寫的代碼較多,也很容易出現(xiàn)異常。在.net中,提供了一個組件BackgroundWorker就是專門解決這個問題的。BackgroundWorker類允許在單獨的專用線程上運行操作。 耗時的操作(如下載和數(shù)據(jù)庫事務)在長時間運行時可能會導致用戶界面(UI)似乎處于停止響應狀態(tài)。如果需要能進行響應的用戶界面,而且面臨與這類操作相關的長時間延遲,則可以使用BackgroundWorker類方便地解決問題。
使用這個組件其實非常簡單,例如,我們做一個類似如下界面的進度條的小例子,在后臺線程中進行耗時運算,同時刷新界面上的進度條。
過程如下:
1.新建一個windows窗體應用程序,如:BackgroundWorkerProgressBarDemo
2.拖一個ProgressBar(progressBar1)和一個BackgroundWorker (backgroundWorker1)到Form上。
3.把下面的代碼copy過去就ok了,代碼注釋的很詳細,可以按照需要修改。
Shown += new EventHandler(Form1_Shown);
// To report progress from the background worker we need to set this property
backgroundWorker1.WorkerReportsProgress = true;
// This event will be raised on the worker thread when the worker starts
backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
// This event will be raised when we call ReportProgress
backgroundWorker1.ProgressChanged += new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
}
void Form1_Shown(object sender, EventArgs e)
{
// Start the background worker
backgroundWorker1.RunWorkerAsync();
}
// On worker thread so do our thing!
void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
// Your background task goes here
for (int i = 0; i <= 100; i++)
{
// Report progress to 'UI' thread
backgroundWorker1.ReportProgress(i);
// Simulate long task
System.Threading.Thread.Sleep(100);
}
}
// Back on the 'UI' thread so we can update the progress bar
void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// The progress percentage is a property of e
progressBar1.Value = e.ProgressPercentage;
}
}
}
若要為后臺操作做好準備,請?zhí)砑覦oWork事件的事件處理程序,在此事件處理程序中調用耗時的操作。
若要開始此操作,請調用RunWorkerAsync。
若要收到進度更新的通知,請?zhí)幚鞵rogressChanged 事件。
若要在操作完成時收到通知,請?zhí)幚鞷unWorkerCompleted 事件。
注意:
您必須非常小心,確保在 DoWork 事件處理程序中不操作任何用戶界面對象。 而應該通過 ProgressChanged 和 RunWorkerCompleted 事件與用戶界面進行通信。
BackgroundWorker 事件不跨 AppDomain 邊界進行封送處理。 請不要使用 BackgroundWorker 組件在多個 AppDomain 中執(zhí)行多線程操作。
如果后臺操作需要參數(shù),請在調用 RunWorkerAsync 時給出參數(shù)。 在 DoWork 事件處理程序內部,可以從 DoWorkEventArgs.Argument 屬性中提取該參數(shù)。
新聞熱點
疑難解答