Handle AggregateException in async routines

  • Test 1
class Program
{
    static async Task WorkAsync()
    {
        Console.WriteLine("Begin WorkAsync");
        await Task.Delay(1000);
        throw new InvalidOperationException();
    }
 
    static void Main(string[] args)
    {
        try {
            WorkAsync().Wait();
        }
        catch (Exception ex) {
            Console.WriteLine($"{ex.GetType().Name} {ex.Message}");
            Console.WriteLine(ex.StackTrace);
        }
    }
}
  • Output
Begin WorkAsync
AggregateException One or more errors occurred.
   at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
   at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
   at System.Threading.Tasks.Task.Wait()
   at ConsoleApp.Program.Main(String[] args) in D:\Workspace\...\Program.cs:line 21
Press any key to continue . . .

为了在同步代码中处理正确的异常,需要做点改进以获取真实的 InnerException:

  • Test 2
class Program
{
    static void OutputException(Exception ex)
    {
        Console.WriteLine($"{ex.GetType().Name} {ex.Message}");
        Console.WriteLine(ex.StackTrace);
    }
 
    static async Task WorkAsync()
    {
        Console.WriteLine("Begin WorkAsync");
        await Task.Delay(1000);
        throw new InvalidOperationException();
    }
 
    static void Main(string[] args)
    {
        try {
            WorkAsync().Wait();
        }
        catch (AggregateException ex) when (ex.InnerException != null) {
            OutputException(ex.InnerException);
        }
        catch (Exception ex) {
            OutputException(ex);
        }
    }
}
Begin WorkAsync
InvalidOperationException Operation is not valid due to the current state of the object.
   at ConsoleApp.Program.d__1.MoveNext() in D:\Workspace\...\Program.cs:line 21
Press any key to continue . . .