使用BackgroundWorker时,出现ProgressChanged延迟的现象,请帮分析下原因

使用BackgroundWorker时,出现ProgressChanged延迟的现象,即我在西面代码的Completed事件中抛出完成时的messageBox,但是因为ProgressChanged的延迟,我的ProgressBar进度条还没满就弹出了对话框,然后progressBar才满……这问题请帮我分析下。 虽说是AsyncOperation.Post()插入消息会延迟,但是ProgressChanged消息是在Completed消息之前插入的啊,至少执行上应该保持队列去执行消息吧???? 代码如下: View Code public partial class BackgroundWorker_Test : Form { private BackgroundWorker worker2 = null; public BackgroundWorker_Test() { InitializeComponent(); worker2 = new BackgroundWorker(); worker2.DoWork += backgroundWorker2_DoWork; worker2.ProgressChanged += backgroundWorker2_ProgressChanged; worker2.RunWorkerCompleted += RunWorkerCompleted; worker2.WorkerSupportsCancellation = true; worker2.WorkerReportsProgress = true; } private void btn_Cancel_Click(object sender, EventArgs e) { if (worker2.IsBusy) { worker2.CancelAsync(); } } private void btn_Start_Click(object sender, EventArgs e) { if (!worker2.IsBusy) { this.progressBar1.Value = 0; worker2.RunWorkerAsync(); } else { MessageBox.Show("正在执行操作,请稍后"); } } private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e) { BackgroundWorker worker2 = sender as BackgroundWorker; int sum = 0; try { for (int i = 1; i <= 100; i++) { if (worker2.CancellationPending) break; Thread.Sleep(20); sum += i; // 进度报告 worker2.ReportProgress(i); } } catch (Exception ex) { throw ex; } if (worker2.CancellationPending) { e.Cancel = true; } else { e.Result = sum; } } private void backgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e) { this.progressBar1.Value = e.ProgressPercentage; } private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { if (e.Error != null) { MessageBox.Show(e.Error.Message); } else if (e.Cancelled) { MessageBox.Show("操作已被取消"); } else { MessageBox.Show(String.Format("操作已完成,结果为:{0}", e.Result)); } } }
潇潇雨雨
浏览 729回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP