我运行这段代码:
var cancellation = new CancellationTokenSource();
var cancelledTask1 = .....;//starting new long-running task that accepts cancellation.Token
var cancelledTask2 = .....;//starting new long-running task that accepts cancellation.Token
//then I request cancellation
cancellation.Cancel();
//some task gets cancelled before code below executes
try
{
//wait for completion (some task is already in cancelled state)
await Task.WhenAll(cancelledTask1, cancelledTask2);
}
catch (OperationCanceledException e)
{
Logger.Debug("await WhenAll", e);
}
我得到
await WhenAll System.Threading.Tasks.TaskCanceledException: A task was canceled.
我认为它是因为某些任务已经处于取消状态而导致的。为什么Task.WhenAll
在取消子任务的情况下方法会中断正常流程并引发异常?这种行为有什么好处?
然后,我尝试以下方法Task.WhenAny
:
var cancellation = new CancellationTokenSource();
var cancelledTask3 = .....;//starting new long-running task that accepts cancellation.Token
//then I request cancellation
cancellation.Cancel();
//the task gets cancelled before code below executes
try
{
//wait for completion (the task is already in cancelled state)
await Task.WhenAny(cancelledTask3);
}
catch (OperationCanceledException e)
{
Logger.Debug("await WhenAny", e);
}
并且它不会抛出异常。
第二个问题是:为什么Task.WhenAny
在同一种情况下不抛出异常?我希望这两种方法都应该以相同的方式处理取消的任务:要么抛出异常,要么不抛出异常。