在e.cancel = true之后,后台工作程序不会运行“RunWorkerCompleted”;

时间:2012-12-17 04:29:31

标签: c# multithreading backgroundworker deadlock

这是dowork代码。我甚至介入过这个。在e.cancel = true之后,DoWork再次运行,它进入while循环,它再次将e.Cancel设置为true,然后退出该函数并且永远不会运行Completed函数。

private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
    {
        BackgroundWorker worker = sender as BackgroundWorker;
        //While the song is not over
          while (!worker.CancellationPending )
          {

              if (progressBar1.Value == progressBar1.Maximum)
              {

                  e.Cancel = true;
                  return;
              }
              else
              {
                  //Keep ticking the progress bar one second
                  worker.ReportProgress(0);
                  Thread.Sleep(1000);
              }
          }
          e.Cancel = true;
          return;



    }

这是取消工作人员的代码。 WaitOne()将阻塞,直到它从RunWorkerCompleted获取信号。

if (this.backgroundWorker2.IsBusy)
        {
            this.backgroundWorker2.CancelAsync();

            _resetEvent.WaitOne();

        }

编辑:请注意,我已完成此VV

backgroundWorker2.RunWorkerCompleted += backgroundWorker2_RunWorkerCompleted;
backgroundWorker2.WorkerSupportsCancellation = true;

1 个答案:

答案 0 :(得分:1)

你设置了

BackgroundWorker.WorkerSupportsCancellation = true