【发布时间】:2020-06-18 23:51:29
【问题描述】:
我有这个代码 sn-p:
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 也不会报告未处理的异常。这很奇怪,我用谷歌搜索,它说 [await] 中有陷阱,但没有解释如何以及为什么。
所以我的问题是,为什么这里没有捕获到异常,使用 await 的陷阱是什么?
非常感谢。
【问题讨论】:
-
好吧,你
RunTask,但你以一劳永逸的方式来做:你不await为执行结果;因此,如果抛出异常,它将仅在任务内。其他还有一个问题:应该在哪个线程(以及何时)重新抛出? -
将您的
Main()方法更改为public static async Task Main(string[] args)和await您对ProcessAsync(null);的调用
标签: c# asynchronous exception async-await throw