且构网

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

是否可以在没有 CancellationToken 的情况下取消 C# 任务?

更新时间:2021-09-21 01:20:43

我读过的***的关于这样做的内容来自 Stephen Toub 在使用 .NET 进行并行编程"博客上.

The best that I have read about doing this is from Stephen Toub on the "Parallel Programming with .NET" blog.

基本上,您创建自己的取消过载":

Basically you create your own cancellation 'overload':

public static async Task<T> WithCancellation<T>( 
    this Task<T> task, CancellationToken cancellationToken) 
{ 
    var tcs = new TaskCompletionSource<bool>(); 
    using(cancellationToken.Register( 
                s => ((TaskCompletionSource<bool>)s).TrySetResult(true), tcs)) 
        if (task != await Task.WhenAny(task, tcs.Task)) 
            throw new OperationCanceledException(cancellationToken); 
    return await task; 
}

然后将其与 try/catch 一起使用以调用您的异步函数:

And then use that with a try/catch to call your async function:

try 
{ 
    await op.WithCancellation(token); 
} 
catch(OperationCanceledException) 
{ 
    op.ContinueWith(t => /* handle eventual completion */); 
    … // whatever you want to do in the case of cancellation 
}

真的需要阅读他的博客帖子...

Really need to read his blog posting...