C# args.Cancel = 真;不停止我的工作线程

C# args.Cancel = true; not stopping my worker thread

我有一个控制某些工业过程的应用程序。其中一些进程非常耗时,因此应用程序创建了一个工作线程来 运行 它们。线程设置为可取消并报告进度。

    CertifyBWThread.WorkerSupportsCancellation = true;
    // this allows the worker to report progress during work
    CertifyBWThread.WorkerReportsProgress = true;

提供了一个按钮,可以在线程正常完成之前将其取消。

if (CertifyBWThread != null)
{
    CertifyBWThread.CancelAsync();
}

作为线程 运行,它会定期检查是否已安排取消。 args 是 DoWorkEventArgs .

//check for cancellation here
if (CertifyBWThread.CancellationPending)
{
    args.Cancel = true;                
}

...我经常在调试器中点击这段代码。一旦我调用了 CancelAsync(),它每次都会通过控制工业过程并将 args.Cancel 设置为 true 的循环触发此操作。但线程 运行s 仍然很有趣。当 args.Cancel 设置为 true 时应该发生什么?

当您的 DoWork() 处理程序检查 CancellationPending 时,仅将 DoWorkEventArgs.Cancel 设置为 true 是不够的。您的 DoWork 处理程序必须 停止工作。

DoWorkEventArgs.Cancel 设置为 true 很重要,因为这就是 BackgroundWorker 对象本身能够区分 DoWork 处理程序返回取消操作并实际 完成 操作返回。这解决了尝试取消操作的代码与操作本身之间可能存在的竞争条件(即,通过这种方式,尝试取消操作的代码可以确定操作是否实际上已被取消,或者它是否在有机会检查之前成功完成关于取消)。

但是 编写你的 DoWork 事件处理程序,这样它实际上会在 CancellationPending 属性 设置为 true.


我根据您问题中不完整的代码示例的推论得出了这个答案。如果以上没有解决您的问题,那么请改进您的问题,以便它包括 a good, minimal, complete code example 可靠地重现问题。