How to better understand the code/statements from “Async - Handling multiple Exceptions” article?

后端 未结 2 787
庸人自扰
庸人自扰 2020-12-18 13:13

Running the following C# console app

class Program
{  static void Main(string[] args)
   {  Tst();
      Console.ReadLine();
   }
   async static Task  Tst(         


        
2条回答
  •  天命终不由人
    2020-12-18 13:31

    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
    

    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.

    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);
    }
    

提交回复
热议问题