问题:有没有办法将 aCancellationToken
与方法Task
返回的值关联起来async
?
通常,如果 a与匹配的's一起抛出, aTask
将最终进入Canceled
状态。如果它们不匹配,则任务进入状态:OperationCancelledException
CancellationToken
Task
CancellationToken
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
从而实现相同的功能)。从我的测试来看,似乎任何 OperationCancelledException
都会导致该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
方法被取消(并且我不希望取消 - 即它不是 thisTask
的CancellationToken
),我希望任务进入Faulted
状态- -不是Canceled
国家。