【发布时间】:2013-02-21 20:02:03
【问题描述】:
问题:有没有办法将CancellationToken 与从async 方法返回的Task 关联起来?
通常,如果OperationCancelledException 与CancellationToken 匹配Task 的CancellationToken 被抛出,Task 将最终处于Canceled 状态。如果它们不匹配,则任务进入Faulted 状态:
void WrongCancellationTokenCausesFault()
{
var cts1 = new CancellationTokenSource();
var cts2 = new CancellationTokenSource();
cts2.Cancel();
// This task will end up in the Faulted state due to the task's CancellationToken
// not matching the thrown OperationCanceledException's token.
var task = Task.Run(() => cts2.Token.ThrowIfCancellationRequested(), cts1.Token);
}
对于async/await,我还没有找到一种方法来设置方法的Task 的CancellationToken(从而实现相同的功能)。从我的测试来看,anyOperationCancelledException 似乎会导致async 方法进入Canceled 状态:
async Task AsyncMethodWithCancellation(CancellationToken ct)
{
// If ct is cancelled, this will cause the returned Task to be in the Cancelled state
ct.ThrowIfCancellationRequested();
await Task.Delay(1);
// This will cause the returned Task to be in the Cancelled state
var newCts = new CancellationTokenSource();
newCts.Cancel();
newCts.Token.ThrowIfCancellationRequested();
}
如果我从async 方法调用的方法被取消(而且我不希望取消——即不是这个Task 的CancellationToken ),我希望任务进入Faulted 状态——而不是Canceled 状态。
【问题讨论】:
标签: c# async-await task-parallel-library cancellation-token