如何使用backgroundWorker保持GUI响应?

时间:2016-04-28 08:22:33

标签: c# wpf multithreading backgroundworker

我的GUI程序(使用WPF,C#)完成了耗时的任务。

由于我希望我的程序在执行期间保持响应,因此我会关注许多关于backgroundWorker类的文章。但它不起作用。

我的程序可以更新其进度条和结果页面。但是在长时间运行的过程中UI不活跃。整个程序UI在启动过程后立即冻结。(我无法点击按钮而不是拖动整个程序)所以我无法实现取消按钮。

BackgroundWorker _backgroundWorker;

private void StartButton(object sender, RoutedEventArgs e)
{
    _backgroundWorker = new BackgroundWorker();
    _backgroundWorker.WorkerReportsProgress = true;
    _backgroundWorker.WorkerSupportsCancellation = true;
    _backgroundWorker.DoWork += _backgroundWorker_DoWork
    _backgroundWorker.ProgressChanged += _backgroundWorker_ProgressChanged;
    _backgroundWorker.RunWorkerCompleted += _backgroundWorker_RunWorkerCompleted;
    _backgroundWorker.RunWorkerAsync(index);
}

private void StopButton(object sender, RoutedEventArgs e)
{
     if (_backgroundWorker.IsBusy)
     {
         _backgroundWorker.CancelAsync();
     }
}

private void _backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
     int index = (int)e.Argument
     for(int i=0; i<index; i++)
     {
          if (_backgroundWorker.CancellationPending == true)
          {
               e.Cancel = true;
               return;
          }

          //Do long-running process
          DataProcessing();

          (sender as BackgroundWorker).ReportProgress(i);
     }
}

private void _backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
     if (e.Cancelled)
     { this.ShowMessageAsync("cancel"); }
     else if (e.Error != null)
     { this.ShowMessageAsync("error"); }
     else
     { this.ShowMessageAsync("complete"); }
}

如果我在_backgroundWorker_Dowork()方法的每次迭代中添加thread.sleep(time),那么我的UI会保持响应。

0 个答案:

没有答案