异步中止C#TPL任务 [英] Asynchronously abort C# TPL Tasks

查看:136
本文介绍了异步中止C#TPL任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法异步中止与 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆