一个任务里抛出异常 - "等待" VS等待() [英] Throw Exception inside a Task - "await" vs Wait()
问题描述
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 关键字时,同样没有发生。结果
什么是这种行为的解释?
In TPL, When throwing an exception inside a Task, it's wrapped with an AggregateException.
But the same is not happening when using the await keyword.
What is the explanation for that behavior ?
推荐答案
我们的目标是让它看起来/像同步版本行为。乔恩斯基特做了伟大的工作,在他的Eduasync系列解释这一点,特别是这篇文章:
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:
<一个href=\"http://$c$cblog.jonskeet.uk/2011/06/22/eduasync-part-11-more-sophisticated-but-lossy-exception-handling/\" rel=\"nofollow\">http://$c$cblog.jonskeet.uk/2011/06/22/eduasync-part-11-more-sophisticated-but-lossy-exception-handling/
这篇关于一个任务里抛出异常 - &QUOT;等待&QUOT; VS等待()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!