异步中止C#TPL任务 [英] Asynchronously abort C# TPL Tasks
问题描述
有没有办法异步中止与 Task.Factory.Create创建的C#TPL任务(()=> {东西});
?我看到有使用的CancellationToken
做这件事的方式,但我想,以避免与 IsCancellationRequested
检查
Is there a way to asynchronously abort C# TPL Tasks created with Task.Factory.Create(() => {stuff});
? I have seen that there is a way of doing it using a CancellationToken
but I like to avoid checking with IsCancellationRequested
.
推荐答案
的的CancellationToken
为在的东西你要使用。检查 IsCancellationRequested
可能看起来像一个痛苦,但它提供了一个干净的方式来处理的取消,而不是创建一个线程,然后放弃它,并不得不处理线程中止异常。在以并行中运行整个代码
The CancellationToken
is the thing you want to use. Checking the IsCancellationRequested
may look like a pain, but it provides a clean way to handle the cancellation, as opposed to creating a thread, then aborting it and having to handle thread aborted exception in the whole code that is being run in parallel.
var cts = new CancellationTokenSource();
var token = cts.Token;
var task = Task.Factory.StartNew(() =>
{
// Do Job Step 1...
if (token.IsCancellationRequested)
{
// Handle cancellation here, if necessary.
// Thanks to @svick - this will set the Task status to Cancelled
// by throwing OperationCanceledException inside it.
token.ThrowIfCancellationRequested();
}
// Do Job Step 2...
// ...
}, token);
// Later, to kill all the tasks and their children, simply:
cts.Cancel();
这可能会增加一些杂乱的代表,但取消本身是那么容易的,我从来没有需要使用任何比取消标记源较粗略的。你有没有说为什么你想避免,所以除非是有严格限制,我会与取消标记坚持。
It may add some clutter to the delegate, but the cancellation itself is so easy that I never needed to use anything cruder than the cancellation token source. You haven't said why you'd like to avoid it, so unless there is some hard limitation, I'd stick with cancellation tokens.
这篇关于异步中止C#TPL任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!