これは、BackgroundWorker の使用の概要を示しています。
private BackgroundWorker _backgroundWorker;
public void Setup( )
{
_backgroundWorker = new BackgroundWorker();
_backgroundWorker.WorkerReportsProgress = true;
_backgroundWorker.DoWork +=
new DoWorkEventHandler(BackgroundWorker_DoWork);
_backgroundWorker.ProgressChanged +=
new ProgressChangedEventHandler(BackgroundWorker_ProgressChanged);
_backgroundWorker.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(BackgroundWorker_RunWorkerCompleted);
// Start the BackgroundWorker
_backgroundWorker.RunWorkerAsync();
}
void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
// This method runs in a background thread. Do not access the UI here!
while (work not done) {
// Do your background work here!
// Send messages to the UI:
_backgroundWorker.ReportProgress(percentage_done, user_state);
// You don't need to calculate the percentage number if you don't
// need it in BackgroundWorker_ProgressChanged.
}
// You can set e.Result = to some result;
}
void BackgroundWorker_ProgressChanged(object sender,
ProgressChangedEventArgs e)
{
// This method runs in the UI thread and receives messages from the backgroud thread.
// Report progress using the value e.ProgressPercentage and e.UserState
}
void BackgroundWorker_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
// This method runs in the UI thread.
// Work is finished! You can display the work done by using e.Result
}
アップデート
この BackgroundWorker は、原因のプレゼンターにある必要があります。MVP、MVC、MVVM などのパターンの考え方は、ビューからできるだけ多くのコードを削除することです。Paint
ビューには、ビューの作成やイベント ハンドラーでの描画など、ビュー自体に非常に固有のコードのみが含まれます。ビュー内の別の種類のコードは、プレゼンターまたはコントローラーと通信するために必要なコードです。ただし、プレゼンテーション ロジックはプレゼンターにある必要があります。
BackgroundWorker_ProgressChanged
UI スレッドで実行されるメソッドを使用して、ビューに変更を送信します。ビューのパブリック メソッドを呼び出すか、ビューのパブリック プロパティを設定するか、ビューのプロパティまたはコントロールのプロパティをバインドしてビューがアタッチできるパブリック プロパティを公開します。(これは MVVM パターンから借用したものです。)INotifyPropertyChanged
ビューをプレゼンターのプロパティにバインドする場合、プロパティが変更されたことをビューに通知するためにプレゼンターを実装する必要があります。
注: UI スレッド以外のスレッドは、ビューを直接操作することはできません (そうしようとすると、例外がスローされます)。したがって、BackgroundWorker_DoWork はビューと直接やり取りできないため、ReportProgress を呼び出します。ReportProgress は、UI スレッドで BackgroundWorker_ProgressChanged を実行します。