c# - 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
好的,抛出了异常,但是主函数的try/catch无法捕获异常,如果我删除try/catch,main也不会报告未处理的异常。这很奇怪,我用谷歌搜索,它说 [await] 中有陷阱,但没有解释如何以及为什么。
所以我的问题是,为什么这里的异常没有被捕获,使用等待的陷阱是什么?
非常感谢。
解决方案
在async
方法中,任何异常都会被运行时捕获并放在返回的Task
. 如果您的代码忽略了方法Task
返回的async
值,那么它将不会观察到这些异常。大多数任务应该await
在某个时候被编辑以观察它们的结果(包括异常)。
最简单的解决方案是使您的Main
异步:
public static async Task Main(string[] args)
{
try
{
await ProcessAsync(null);
}
catch(Exception e)
{
Console.WriteLine(e.Message);
}
}
推荐阅读
- python - 为 python 项目设置虚拟环境
- javascript - 无法使用 javascript 读取 JSON 文件
- python - 禁用 Kivy Carousel 上的滑动操作
- python - 如何将所有行写入 csv 文件,而不仅仅是最后一行?
- ruby-on-rails - 带有 jsonapi-serializers 的条件属性抛出 TypeError
- reactjs - 获取靠近我的位置的坐标数组反应原生
- sql - ORA-00999: 无效的视图名称 - 有什么问题?
- python - 芹菜工人在高负荷下反应迟钝
- cppcheck - 带有自定义 Malloc 函数的 CppCheck
- image - Thingsboard 3 导出图表到图像