BackgroundWorker 使用 RunWorkerCompleted 和 ReportProgress 事件与主线程通信。RunWorkerCompleted 应该做您需要做的事情,因为一旦后台工作完成,它将在 UI 线程上执行。
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
LongComputation();
};
// RunWorkerCompleted will fire on the UI thread when the background process is complete
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
if (args.Error != null)
{
// an exception occurred on the background process, do some error handling
}
MyView.UpdateStatus("Ready");
};
MyView.UpdateStatus("Please wait");
worker.RunWorkerAsync();
此外,您可以使用 RunWorkerCompleted 使用 DoWorkerEventArgs 的 Result 属性将结果编组回主线程。
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
args.Result = LongComputation();
};
worker.rep
// RunWorkerCompleted will fire on the UI thread when the background process is complete
worker.RunWorkerCompleted += delegate(object s, RunWorkerCompletedEventArgs args)
{
if (args.Error != null)
{
// an exception occurred on the background process, do some error handling
}
var result = args.Result;
// do something on the UI with your result
MyView.UpdateStatus("Ready");
};
最后,您可以在后台进程的逻辑步骤中使用 ReportProgress 事件来更新 UI:
worker.DoWork += delegate(object s, DoWorkEventArgs args)
{
FirstHalfComputation();
// you can report a percentage back to the UI thread, or you can send
// an object payload back
int completedPercentage = 50;
object state = new SomeObject();
worker.ReportProgress(completedPercentage , state);
SecondHalfComputation();
};
worker.WorkerReportsProgress = true; // this is important, defaults to false
worker.ProgressChanged += delegate(object s, ProgressChangedEventArgs args)
{
int completedPercentage = args.ProgressPercentage;
SomeObject state = args.UserState as SomeObject
// update a progress bar or do whatever makes sense
progressBar1.Step = completedPercentage;
progressBar1.PerformStep();
};