Why do unawaited async methods not throw exception

2019-04-20 04:16发布

问题:

I thought that async methods were supposed to behave like normal methods until they arrived at an await.

Why does this not throw an exception?

Is there a way to have the exception thrown without awaiting?

using System;
using System.Threading.Tasks;

public class Test
{
    public static void Main()
    {
        var t = new Test();
        t.Helper();
    }

    public async Task Helper()
    {
        throw new Exception();
    }
}

回答1:

An exception thrown inside an async method is, by design, stored inside the returned task. To get your hands on the exception you can:

  1. await the task: await t.Helper();
  2. Wait the task: t.Helper().Wait();
  3. Check the task's Exception property after the task has been completed: var task = t.Helper(); Log(task.Exception);
  4. Add a continuation to that task that handles the exception: t.Helper().ContinueWith(t => Log(t.Exception), TaskContinuationOptions.OnlyOnFaulted);

Your best option is the first one. Simply await the task and handle the exception (unless there's a specific reason you can't do that). More in Task Exception Handling in .NET 4.5