且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

异步中止C#TPL任务

更新时间:2023-11-21 18:03:04

的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.