我正在进行代码审查,我很担心这种模式,在整个代码中都可以看到:
try
{
await DoSomethingAsync();
await DoSomethingElseAsync();
// and so on...
}
catch (OperationCanceledException)
{
// all good, user cancelled
// log and return
return;
}
// handle other particular exceptions
// ...
catch (Exception ex)
{
// fatal error, alert the user
FatalErrorMessage(ex);
}
我关心的部分是处理 OperationCanceledException
。这段代码不应该也处理 AggregateException
并检查唯一的 inner 异常是 OperationCanceledException
吗?
我知道 Task.Wait
或 Task.Result
会像那样抛出 AggregateException
,而不是 OperationCanceledException
.代码的作者向我保证,她只从内到外使用 async/await
,从不使用 Wait/Result
。因此,她不喜欢额外观察 AggregateException
以进行取消的想法。然而,我的观点是一些标准的基于 Task
的 BCL API 仍然可以使用 AggregateException
包装 OperationCanceledException
,例如因为他们仍然可能在内部访问 Task.Result
。
有意义吗?我们是否应该担心同时处理 OperationCanceledException
和 AggregateException
以正确观察取消?
最佳答案
However, my point is some standard Task-based BCL APIs could still be wrapping OperationCanceledException with AggregateException, e.g. because they still might be accessing Task.Result internally.
不,他们不会那样做。
Should we be worrying about handling both OperationCanceledException and AggregateException to observe cancellation correctly?
我会说不。当然,可能AggregateException
可以包含OperationCanceledException
,但它也可以包含其他特定异常
同样容易。
只要您遵循异步最佳实践(即没有异步同步或异步同步),那么您就不必担心这一点。
关于c# - 正确处理任务取消的一般方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28081819/