BackgroundWorker 元件概觀
有許多經常執行的作業都需要長時間執行。 例如:
映像下載
Web 服務叫用
檔案下載及上傳 (包括對等應用程式)
複雜的本機運算
資料庫交易
本機磁碟存取 (假設因為存取記憶體導致速度變慢)
這類作業可能會導致使用者介面在執行時封鎖。 當您需要 UI 即時回應,但 UI 卻受到這些作業拖累,導致回應時間拉長時,BackgroundWorker 元件可以提供合宜的解決方法。
BackgroundWorker 元件可以非同步 (在背景中) 的方式,透過不同於應用程式之主要 UI 執行緒的執行緒來執行這些耗時的作業。 若要使用 BackgroundWorker,只須告知此函式要在背景中執行哪一個工作者方法,然後再呼叫 RunWorkerAsync 方法就可以了。 您呼叫的執行緒會如常執行,而工作者方法也會以非同步的方式同時執行。 當方法結束時,BackgroundWorker 會引發 RunWorkerCompleted 事件來提示您呼叫的執行緒,並視情況在事件中包含作業的結果。
元件 BackgroundWorker 可從 [工具箱 ] 的 [元件 ] 索引標籤中 取得。 若要將 新增 BackgroundWorker 至表單,請將 BackgroundWorker 元件拖曳到表單上。 它會出現在元件匣中,其屬性會出現在 [屬性 ] 視窗中。
若要啟動非同步作業,請使用 RunWorkerAsync 方法。 RunWorkerAsync 可接受選用的 object
參數將引數傳遞給您的工作者方法。 BackgroundWorker 類別會引發 DoWork 事件,而您的工作者執行緒會經由 DoWork 事件處理常式連結至此事件。
DoWork 事件處理常式可接受具有 DoWorkEventArgs 屬性的 Argument 參數。 此屬性會從 RunWorkerAsync 接收參數,並可傳遞給 DoWork 事件處理常式中所呼叫的工作者方法。 下列範例示範如何指派工作者方法 ComputeFibonacci
所產生的結果。 它是較大範例的一部分,您可以在 如何:實作使用背景作業 的表單。
// This event handler is where the actual,
// potentially time-consuming work is done.
void backgroundWorker1_DoWork( Object^ sender, DoWorkEventArgs^ e )
{
// Get the BackgroundWorker that raised this event.
BackgroundWorker^ worker = dynamic_cast<BackgroundWorker^>(sender);
// Assign the result of the computation
// to the Result property of the DoWorkEventArgs
// object. This is will be available to the
// RunWorkerCompleted eventhandler.
e->Result = ComputeFibonacci( safe_cast<Int32>(e->Argument), worker, e );
}
// This event handler is where the actual,
// potentially time-consuming work is done.
private void backgroundWorker1_DoWork(object sender,
DoWorkEventArgs e)
{
// Get the BackgroundWorker that raised this event.
BackgroundWorker worker = sender as BackgroundWorker;
// Assign the result of the computation
// to the Result property of the DoWorkEventArgs
// object. This is will be available to the
// RunWorkerCompleted eventhandler.
e.Result = ComputeFibonacci((int)e.Argument, worker, e);
}
' This event handler is where the actual work is done.
Private Sub backgroundWorker1_DoWork( _
ByVal sender As Object, _
ByVal e As DoWorkEventArgs) _
Handles backgroundWorker1.DoWork
' Get the BackgroundWorker object that raised this event.
Dim worker As BackgroundWorker = _
CType(sender, BackgroundWorker)
' Assign the result of the computation
' to the Result property of the DoWorkEventArgs
' object. This is will be available to the
' RunWorkerCompleted eventhandler.
e.Result = ComputeFibonacci(e.Argument, worker, e)
End Sub
如需使用事件處理常式的詳細資訊,請參閱 事件 。
警告
無論使用何種多執行緒作業,您都可能會面臨嚴重而複雜的錯誤。 請在實作使用多執行緒的任何解決方案之前參閱 Managed 執行緒最佳做法。
如需使用 BackgroundWorker 類別的詳細資訊,請參閱 如何:在背景 中執行作業。
另請參閱
意見反應
https://aka.ms/ContentUserFeedback。
即將登場:在 2024 年,我們將逐步淘汰 GitHub 問題作為內容的意見反應機制,並將它取代為新的意見反應系統。 如需詳細資訊,請參閱:提交並檢視相關的意見反應