[英]How to stop BackgroundWorker whose `DoWork` handler only contains one (long-running) statement?
I have a problem with a BackgroundWorker
whose DoWork
handler contains only one statement. 我的
BackgroundWorker
的DoWork
处理程序仅包含一个语句,我遇到了问题。 Which means that I cannot check the CancellationPending
flag: 这意味着我无法检查
CancellationPending
标志:
private void BackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
CallTimeConsumerFunction();
}
How can I stop this BackgroundWorker
? 如何停止此
BackgroundWorker
? Is there any work-around? 有什么解决方法吗?
Looking at .NET 4's Task Parallel Library (TPL), which came after BackgroundWorker
and is rather well-designed, can give you an idea how you should approach this. 查看.NET 4的Task Parallel Library(TPL)(在
BackgroundWorker
之后)并且经过了精心设计,可以使您了解如何实现此目标。
Cancellation in the TPL is built on the idea of cooperative cancellation . TPL中的取消基于合作取消的思想 。 This means that tasks are not forcibly stopped from the outside;
这意味着任务不会从外部被强制停止; instead they participate in the cancellation process by periodically checking whether cancellation has been requested and, if so, by gracefully aborting "from the inside".
相反,他们通过定期检查是否已请求取消,如果是,则通过优雅地中止“从内部”参与取消过程。
I recommend you follow the TPL's example and implement cooperative cancellation. 我建议您遵循TPL的示例并实施合作取消。 Like this comment states, inject cancellation logic into
CallTimeConsumerFunction
. 像此注释状态一样,将取消逻辑注入
CallTimeConsumerFunction
。 For example: 例如:
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);
} // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.