星期五, 2月 24, 2017

[C#] BackgroundWorker

四篇筆記
的 BackgroundWorker 筆記重點整理


Property

Property 說明
WorkerReportsProgress是否報告進度更新
CancellationPending支援非同步取消作業
WorkerSupportsCancellationDoWork Eevent 內,用來判斷應用程式是否已要求取消
IsBusyBackgroundWorker 是否正在執行非同步作業

Method

Method 說明
RunWorkerAsync()執行背景作業,觸發 DoWork Event
ReportProgress()DoWork Event 內,觸發 ProgressChanged Event
CancelAsync()取消背景作業

Event

Event說明
DoWorkRunWorkerAsync() 會觸發 DoWork Event,背景作業要放在這裡處理
ProgressChangedReportProgress() 會觸發 ProgressChanged Event,負責進度顯示
RunWorkerCompleted背景作業完成時觸發

官方文件說明
You must be careful not to manipulate any user-interface objects in your DoWork event handler. Instead, communicate to the user interface through the ProgressChanged and RunWorkerCompleted events.
DoWork 為非同步作業,ProgressChanged 和 RunWorkerCompleted 仍然是在 main thread 內進行作業

Property 和 Method 對應表

當 Property = true 時,才可以使用 Method

PropertyMethod
WorkerReportsProgressReportProgress
WorkerSupportsCancellationCancelAsync

Method 觸發 Event 對應表


MethodEvent
RunWorkerAsyncDoWork
ReportProgressProgressChanged
EventAtgs

DoWorkEventArgs

EventArgs說明
Argument取得 RunWorkerAsync() 參數
Cancel停止背景作業
Result設定背景作業結果

ProgressChangedEventArgs

EventArgs說明
ProgressPercentage背景作業進度百分比,ReportProgress() 的 percentProgress 參數
UserStateReportProgress() 的 userState 參數

RunWorkerCompletedEventArgs

EventArgs說明
Cancelled是否已取消背景作業
Error背景作業執行時,是否發生錯誤
Result背景作業結果,取得 DoWorkEventArgs.Result property 設定值

參數傳遞表

[C#] BackgroundWorker-1
[C#] BackgroundWorker-2
Exception Handle

DoWork 內發生 Exception,必須在 RunWorkerCompleted Event 內透過 RunWorkerCompletedEventArgs.Error 來處理

官方文件說明
If the operation raises an exception that your code does not handle, the BackgroundWorker catches the exception and passes it into the RunWorkerCompleted event handler, where it is exposed as the Error property of System.ComponentModel.RunWorkerCompletedEventArgs. If you are running under the Visual Studio debugger, the debugger will break at the point in the DoWork event handler where the unhandled exception was raised. If you have more than one BackgroundWorker, you should not reference any of them directly, as this would couple your DoWork event handler to a specific instance of BackgroundWorker. Instead, you should access your BackgroundWorker by casting the sender parameter in your DoWork event handler.

沒有留言:

張貼留言