总而言之,我已经知道BackgroundWorker在WinForm中处理多线程案例的基本用法.代码结构如下所示.
在应用程序的主线程中.刚刚启动BackgroundWork.
if (backgroundWorker1.IsBusy != true) { // Start the asynchronous operation. backgroundWorker1.RunWorkerAsync(); }
然后它会触发DoWork事件.所以我们可以在那里做点什么.
private void backgroundWorker1_DoWork(object sender,DoWorkEventArgs e) { BackgroundWorker worker = sender as BackgroundWorker; ...... // report progress. worker.ReportProgress(iProgress); .... }
然后我们只需要处理ProgressChanged事件以显示BackgroundWorker进度.
private void backgroundWorker1_ProgressChanged(object sender,ProgressChangedEventArgs e) { //show progress. resultLabel.Text = (e.ProgressPercentage.ToString() + "%"); }
DoWork完成或发生异常后.将触发RunWorkerCompleted事件.
这是我对这个事件处理的问题.请帮助审查它们.谢谢.
我注意到RunWorkerCompletedEventArgs中有一个名为’Result’的属性,它用于什么?我怎么用呢?
是否有可能接收我的自定义异常消息而不是e.error?如果有,如何制作?
private void backgroundWorker1_RunWorkerCompleted(object sender,RunWorkerCompletedEventArgs e) { if (e.Cancelled == true) { resultLabel.Text = "Canceled!"; } else if (e.Error != null) { resultLabel.Text = "Error: " + e.Error.Message; } else { resultLabel.Text = e.Result.ToString(); } }