取消任务并将状态设置为"已取消"

时间:2017-05-11 10:25:59

标签: c# task cancellationtokensource aggregateexception

我希望在50毫秒结束时完成一项任务。然后,任务的状态应设置为" 已取消"否则设置为" RunToCompletion "。

任务创建在这里:

CancellationTokenSource cts = new CancellationTokenSource(50);
CancellationToken ct = cts.Token;
Task test_task = Task.Run(async () =>
{
    try
    {
        tokenS.Token.Register(() =>
        {
            cts.Cancel();
            ct.ThrowIfCancellationRequested();
        });
        await NotifyDevice(BLEDevice);
    }
    catch (Exception e)
    {
    }
},ct);

直到现在我所有人都是AggregateException,不会被try/catch - 块以某种方式捕获。

1 个答案:

答案 0 :(得分:1)

以下是与您类似的问题:Is it possible to cancel a C# Task without a CancellationToken?。但该解决方案不会取消NotifyDevice方法中的任务。仅当基础任务支持取消时,才能取消该任务。并且基于文档I​Async​Info可以取消。我会使用包装器来确保在50ms内取消任务,以防取消基础任务需要更多时间:

CancellationTokenSource cts = new CancellationTokenSource(50);
await NotifyDevice(BLEDevice, cts.Token).WithCancellation(cts.Token);

编辑:扩展方法本身:

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; 
}