且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-12-04 20:12:53

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