本文介绍了如何取消HostingEnvironment.QueueBackgroundWorkItem的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以取消使用 HostingEnvironment.QueueBackgroundWorkItem
进行的后台任务?
Is there a way to cancel background task made with HostingEnvironment.QueueBackgroundWorkItem
?
有 CancellationToken
通知任务是否被取消,但是我该怎么办?
引用
There is CancellationToken
which notifies if tasks was cancelled but how can i do it?Refering to https://msdn.microsoft.com/en-us/library/dd997396(v=vs.110).aspx
确定。经过几次试验后,我在哪里可以访问 CancellationTokenSource
?
OK. Where can i get access to CancellationTokenSource
?
推荐答案
提出了解决方案:
HostingEnvironment.QueueBackgroundWorkItem(ct =>
{
var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(ct);
var cancellationToken = linkedTokenSource.Token;
return Task.Factory.StartNew(() =>
{
// do stuff on background
}, cancellationToken);
});
更新:
实际上,不需要任务。感谢svick提出来。
这是没有任务的更详细的代码示例。
Indeed, task is not needed. Thanks svick for bringing that up.Here is a bit more detailed code sample without task.
HostingEnvironment.QueueBackgroundWorkItem(ct =>
{
var linkedTokenSource = CancellationTokenSource.CreateLinkedTokenSource(ct);
// following is a dummy method, but you get the idea.
// StoreCancellationTokenSourceSoItCanBeUsedSomewhereElse(linkedTokenSource);
var cancellationToken = linkedTokenSource.Token;
try
{
while(true)
{
cancellationToken.ThrowIfCancellationRequested();
// do bg stuff
}
}
catch (OperationCanceledException ex)
{
// either token is in cancelled state
}
});
这篇关于如何取消HostingEnvironment.QueueBackgroundWorkItem的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!