在任务中抛出异常 - “await”与等待()
static async void Main(string[] args)
{
Task t = new Task(() => { throw new Exception(); });
try
{
t.Start();
t.Wait();
}
catch (AggregateException e)
{
// When waiting on the task, an AggregateException is thrown.
}
try
{
t.Start();
await t;
}
catch (Exception e)
{
// When awating on the task, the exception itself is thrown.
// in this case a regular Exception.
}
}
在 TPL 中,当在任务中抛出异常时,它会被 AggregateException 包装起来。
但使用 await 关键字时,不会发生同样的情况。
这种行为的解释是什么?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
目标是使其看起来/表现得像同步版本。 Jon Skeet 在他的 Eduasync 系列中对此做了很好的解释,特别是这篇文章:
http://codeblog.jonskeet.uk/2011/06/22/eduasync-part-11-more-sophisticated-but-lossy-exception-handling/
The goal is to make it look/act like the synchronous version. Jon Skeet does a great job explaining this in his Eduasync series, specifically this post:
http://codeblog.jonskeet.uk/2011/06/22/eduasync-part-11-more-sophisticated-but-lossy-exception-handling/
在 TPL 中使用 AggregateException 是因为等待操作中可以有多个任务(任务可以附加子任务),因此其中许多任务都可以抛出异常。请查看此处的子任务中的异常部分:
https://msdn.microsoft.com/ru-ru/library/dd997417(v=vs.110).aspx
中
await
你总是只有一项任务。另请参阅 https://msdn.microsoft.com /ru-ru/library/dd997415(v=vs.110).aspx
In TPL
AggregateException
is used because you can have multiple tasks in wait operation (task can have child tasks attached), so many of them can throw exceptions. Look at Exceptions in child tasks section here:https://msdn.microsoft.com/ru-ru/library/dd997417(v=vs.110).aspx
In
await
you always have just one task.See also https://msdn.microsoft.com/ru-ru/library/dd997415(v=vs.110).aspx
Stephen Toub 详细解释了为什么 Task.Wait() 和 wait 之间的异常类型不同:
.NET 4.5 中的任务异常处理
Here is a good explanation in details, by Stephen Toub, why there is a difference in exception type between Task.Wait() and await:
Task Exception Handling in .NET 4.5