【问题标题】:How to stop BackgroundWorker whose `DoWork` handler only contains one (long-running) statement?如何停止其`DoWork`处理程序仅包含一个(长时间运行)语句的BackgroundWorker?
【发布时间】:2015-08-29 21:52:58
【问题描述】:

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

private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
    CallTimeConsumerFunction();
}

我怎样才能阻止这个BackgroundWorker?有什么解决办法吗?

【问题讨论】:

  • 你应该将取消逻辑注入CallTimeConsumerFunction()

标签: c# multithreading backgroundworker cancellation


【解决方案1】:

查看 .NET 4 的任务并行库 (TPL),它位于 BackgroundWorker 之后并且设计得相当好,可以让您了解应该如何处理这个问题。

Cancellation in the TPL is built on the idea of cooperative cancellation。这意味着任务不会从外部强制停止;相反,他们通过定期检查是否已请求取消来参与取消过程,如果是,则通过“从内部”优雅地中止。

我建议您遵循 TPL 的示例并实施合作取消。与this comment 状态一样,将取消逻辑注入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);
}                         // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    • 2012-09-09
    • 1970-01-01
    • 2015-03-08
    • 2012-05-31
    • 2016-07-23
    • 2023-03-03
    相关资源
    最近更新 更多