c# - e.cancel = true 后后台worker不会运行 "RunWorkerCompleted";

标签 c# multithreading backgroundworker deadlock

这是工作代码。我什至已经完成了这个。 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;



    }

这是取消 worker 的代码。 WaitOne() 将阻塞,直到它收到来自 RunWorkerCompleted 的信号。

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

            _resetEvent.WaitOne();

        }

编辑:请注意,我已经完成了这个 VV

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

最佳答案

你设置了吗

BackgroundWorker.WorkerSupportsCancellation = true

?

关于c# - e.cancel = true 后后台worker不会运行 "RunWorkerCompleted";,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13908271/

相关文章:

c# - 正则表达式类 - 缺少程序集引用?

c# - 如何通过以下语法访问 C# 字典元素?

c# - (Wix 安装程序)如何包含自定义操作依赖项

iphone - UIWebView 中的异步 HTTP 请求真的会产生新线程吗?

c++ - 检查函数内的当前线程是否正常?

c# - 从 Collection 类中提取数据

c# - 从主线程调用 WPF 窗口中的方法

c# - 如何在不卡住 GUI C# Winform 的情况下将组合框值传递给 BackgroundWorker

c# - 根据 .NET backgroundworker 的结果更新变量

c# - C#更改另一个线程上的表单字符串