Tro*_*yvs 1 c# asynchronous exception throw async-await
我有这个代码片段:
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
它运行并打印:
call function
throw
Run Code Online (Sandbox Code Playgroud)
好的,抛出异常,但是主函数的 try/catch 无法捕获异常,如果我删除 try/catch,main 也不会报告未处理的异常。这很奇怪,我用谷歌搜索,它说 [await] 中有陷阱,但没有解释如何以及为什么。
所以我的问题是,为什么这里没有捕获异常,使用 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);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
211 次 |
| 最近记录: |