C# 如何阻止BackgroundWorker的“DoWork”处理程序只包含一条(长时间运行)语句?

C# 如何阻止BackgroundWorker的“DoWork”处理程序只包含一条(长时间运行)语句?,c#,multithreading,backgroundworker,cancellation,C#,Multithreading,Backgroundworker,Cancellation,我遇到了一个BackgroundWorker的问题,他的DoWork处理程序只包含一条语句。这意味着我无法检查CancellationPending标志: 我怎样才能阻止这个幕后工作者?有什么解决办法吗?看看.NET 4的任务并行库TPL,它是在BackgroundWorker之后出现的,设计得相当好,可以让你知道应该如何处理这个问题 。这意味着任务不会从外部强制停止;相反,他们通过定期检查是否已请求取消来参与取消过程,如果是,则从内部优雅地中止 我建议您以第三方物流为例,实施合作取消。与状态类

我遇到了一个BackgroundWorker的问题,他的DoWork处理程序只包含一条语句。这意味着我无法检查CancellationPending标志:


我怎样才能阻止这个幕后工作者?有什么解决办法吗?

看看.NET 4的任务并行库TPL,它是在BackgroundWorker之后出现的,设计得相当好,可以让你知道应该如何处理这个问题

。这意味着任务不会从外部强制停止;相反,他们通过定期检查是否已请求取消来参与取消过程,如果是,则从内部优雅地中止

我建议您以第三方物流为例,实施合作取消。与状态类似,将取消逻辑注入CallTimeConsumerFunction。例如:

void CallTimeConsumerFunction(Func<bool> shouldCancel)
{                          // ^^^^^^^^^^^^^^^^^^^^^^^
                           // add this; can be called to find out whether to abort or not
    … // possibly lengthy operation
    if (shouldCancel()) return;
    … // possibly lengthy operation
}

private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    CallTimeConsumerFunction(shouldCancel: () => backgroundWorker.CancellationPending);
}                         // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

您应该将取消逻辑注入CallTimeConsumerFunction
void CallTimeConsumerFunction(Func<bool> shouldCancel)
{                          // ^^^^^^^^^^^^^^^^^^^^^^^
                           // add this; can be called to find out whether to abort or not
    … // possibly lengthy operation
    if (shouldCancel()) return;
    … // possibly lengthy operation
}

private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    CallTimeConsumerFunction(shouldCancel: () => backgroundWorker.CancellationPending);
}                         // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^