为什么unawaited异步方法不会抛出异常?

Cra*_*aig 11 .net c# error-handling asynchronous async-await

我认为异步方法应该像普通方法一样,直到他们到达等待.

为什么这不会抛出异常?

有没有办法在没有等待的情况下抛出异常?

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

i3a*_*non 16

async设计中,抛出的异常是存储在返回的任务中.要获得例外,您可以:

  1. await 任务: await t.Helper();
  2. Wait 任务: t.Helper().Wait();
  3. 任务完成检查任务的Exception属性:var task = t.Helper(); Log(task.Exception);
  4. 为处理异常的任务添加延续: t.Helper().ContinueWith(t => Log(t.Exception), TaskContinuationOptions.OnlyOnFaulted);

你最好的选择是第一个.只是await任务和处理异常(除非有特殊原因你不能这样做).更多在.NET 4.5中的任务异常处理