简体   繁体   English

C#:在没有 [await] 的情况下调用 [async] 方法不会捕获其抛出的异常?

[英]C#: calling [async] method without [await] will not catch its thrown exception?

I'm having this code snippet:我有这个代码片段:

class Program
{
    public static async Task ProcessAsync(string s)
    {
        Console.WriteLine("call function");
        if (s == null)
        {
            Console.WriteLine("throw");
            throw new ArgumentNullException("s");
        }
        Console.WriteLine("print");
        await Task.Run(() => Console.WriteLine(s));
        Console.WriteLine("end");
    }
    public static void Main(string[] args)
    {
        try
        {
            ProcessAsync(null);
        }
        catch(Exception e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

It runs and prints:它运行并打印:

call function
throw

Ok, and exception is thrown, but the main function's try/catch is not able to catch the exception, if I remove the try/catch, main doesn't report unhandled exception either.好的,抛出异常,但是主函数的 try/catch 无法捕获异常,如果我删除 try/catch,main 也不会报告未处理的异常。 This is very weird, I googled and it says there's trap in [await] but doesn't explain how and why.这很奇怪,我用谷歌搜索,它说 [await] 中有陷阱,但没有解释如何以及为什么。

So my question, why here the exception is not caught, what's the pitfalls of using await?所以我的问题是,为什么这里没有捕获异常,使用 await 的陷阱是什么?

Thanks a lot.非常感谢。

Within an async method, any exceptions are caught by the runtime and placed on the returned Task . async方法中,任何异常都会被运行时捕获并放置在返回的Task If your code ignores the Task returned by an async method, then it will not observe those exceptions.如果您的代码忽略async方法返回的Task ,则不会观察到这些异常。 Most tasks should be await ed at some point to observe their results (including exceptions).大多数任务应该在某个时候await以观察它们的结果(包括异常)。

The easiest solution is to make your Main asynchronous:最简单的解决方案是使您的Main异步:

public static async Task Main(string[] args)
{
  try
  {
    await ProcessAsync(null);
  }
  catch(Exception e)
  {
    Console.WriteLine(e.Message);
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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