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

问题描述 投票:0回答:1

我有此代码段:

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

它运行并打印:

call function
throw

确定,并且引发了异常,但是主函数的try / catch无法捕获异常,如果我删除了try / catch,main也不会报告未处理的异常。这很奇怪,我在Google上搜索了一下,并说[await]中存在陷阱,但没有解释如何以及为什么。

所以,我的问题是,为什么这里没有捕获到异常,所以使用await有什么陷阱?

非常感谢。

c# asynchronous exception async-await throw
1个回答
1
投票

Within an async method, any exceptions are caught by the runtime and placed on the returned Task。如果您的代码忽略了async方法返回的Task,则它将不会观察到这些异常。大多数任务都应在某个时间点Task以观察其结果(包括异常)。

最简单的解决方案是使async异步:

await
© www.soinside.com 2019 - 2024. All rights reserved.