[英]C#: calling [async] method without [await] will not catch its thrown exception?
我有这个代码片段:
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] 中有陷阱,但没有解释如何以及为什么。
所以我的问题是,为什么这里没有捕获异常,使用 await 的陷阱是什么?
非常感谢。
在async
方法中,任何异常都会被运行时捕获并放置在返回的Task
。 如果您的代码忽略async
方法返回的Task
,则不会观察到这些异常。 大多数任务应该在某个时候await
以观察它们的结果(包括异常)。
最简单的解决方案是使您的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.