在任务中抛出异常 - "等待"与等待()

Yar*_*evi 20 c# exception-handling parallel-extensions task-parallel-library async-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.
    }           
}
Run Code Online (Sandbox Code Playgroud)

在TPL中,当在Task中抛出异常时,它被包装为AggregateException.
但是使用await关键字时也不会发生同样的情况.
这种行为的解释是什么?

Jam*_*ing 10

目标是使其看起来/行为像同步版本.Jon Skeet在他的Eduasync系列中做了很好的解释,特别是这篇文章:

http://codeblog.jonskeet.uk/2011/06/22/eduasync-part-11-more-sophisticated-but-lossy-exception-handling/


小智 5

在 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

  • 英文链接为:https://msdn.microsoft.com/en-us/library/dd997417(v=vs.110).aspx 和 https://msdn.microsoft.com/en-us/library/dd997415( v=vs.110).aspx (2认同)