且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何更好地理解code /距离报表和QUOT;异步 - 处理多个异常"文章?

更新时间:2021-12-21 23:03:55

这篇文章是错误的。当您运行code时,的await ED 工作包含看起来像这样的异常:

The article is wrong. When you run your code, the awaited Task contains an exception that looks something like this:

AggregateException
  AggregateException
    NullReferenceException
  AggregateException
    ArgumentException

什么等待(或,更具体地,TaskAwaiter.GetResult()$c$c>)在这里所做的是,它需要外部 AggregateException 键,重新抛出了第一个孩子例外。在这里,这是另一个 AggregateException ,所以这是什么异常。

What await (or, more specifically, TaskAwaiter.GetResult()) does here is that it takes the outer AggregateException and rethrows its first child exception. Here, that's another AggregateException, so that's what is thrown.

code其中一个工作有多个异常,其中一人后直接重新抛出的例子等待是使用 Task.WhenAll()而不是 AttachedToParent

Example of code where a Task has multiple exceptions and one of them is directly rethrown after await would be to use Task.WhenAll() instead of AttachedToParent:

try
{
    await Task.WhenAll(
        Task.Factory.StartNew(() => { throw new NullReferenceException(); }),
        Task.Factory.StartNew(() => { throw new ArgumentException(); }));
}
catch (AggregateException ex)
{
    // this catch will never be target
    Console.WriteLine("** {0} **", ex.GetType().Name);
}
catch (Exception ex)
{
    Console.WriteLine("## {0} ##", ex.GetType().Name);
}