c# - 正确处理任务取消的一般方法

标签 c# .net task-parallel-library async-await cancellation

我正在进行代码审查,我很担心这种模式,在整个代码中都可以看到:

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.WaitTask.Result 会像那样抛出 AggregateException,而不是 OperationCanceledException .代码的作者向我保证,她只从内到外使用 async/await,从不使用 Wait/Result。因此,她不喜欢额外观察 AggregateException 以进行取消的想法。然而,我的观点是一些标准的基于 Task 的 BCL API 仍然可以使用 AggregateException 包装 OperationCanceledException,例如因为他们仍然可能在内部访问 Task.Result

有意义吗?我们是否应该担心同时处理 OperationCanceledExceptionAggregateException 以正确观察取消?

最佳答案

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/

相关文章:

c# - 反编译的 C# 是否从 IL/MSIL 进行逆向工程?

c# - 如何在自分层树结构中的每个节点执行业务规则

c# - LINQ to Entities 无法识别该方法

c# - 如何处理 Task.Factory.StartNew 异常?

.net - 使用 .NET 4.0 中的任务并行库等待所有任务完成

c# - 在没有子类化面板的情况下禁用 OnPaintBackground?

c# - 应用于类的不变性

.net - CIL 中的分支

c# - Parallel.ForEach 中的迭代器在多个线程上运行

c# - 使用 LINQ to XML 在 XML 元素内对双引号进行编码