C#:在没有[await]的情况下调用[async]方法不会捕获其引发的异常吗? [英] C#: calling [async] method without [await] will not catch its thrown exception?

查看:161
本文介绍了C#:在没有[await]的情况下调用[async]方法不会捕获其引发的异常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码段:

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

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

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. 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?

非常感谢.

推荐答案

async 方法内,运行时将捕获所有异常并将其放置在返回的 Task 上.如果您的代码忽略了 async 方法返回的 Task ,则它将不会观察到这些异常.大多数任务都应该在某个时候 await 以观察其结果(包括异常).

Within an async method, any exceptions are caught by the runtime and placed on the returned Task. If your code ignores the Task returned by an async method, then it will not observe those exceptions. Most tasks should be awaited at some point to observe their results (including exceptions).

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

The easiest solution is to make your Main asynchronous:

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

这篇关于C#:在没有[await]的情况下调用[async]方法不会捕获其引发的异常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆