简体   繁体   中英

Why do unawaited async methods not throw exceptions?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM