Csharp/C#教程:在任务中抛出exception – “等待”与等待()分享


在任务中抛出exception – “等待”与等待()

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中,当在Task中抛出一个exception时,它被一个AggregateException包装。
但是使用await关键字时也不会发生同样的情况。
这种行为的解释是什么?

目标是使其外观/行为与同步版本相同。 Jon Skeet在他的Eduasync系列中做了很好的解释,特别是这篇文章:

Eduasync part 11: More sophisticated (but lossy) exception handling

在TPL中使用AggregateException是因为在等待操作中可以有多个任务(任务可以附加子任务),因此很多任务都可以抛出exception。 查看子任务部分中的例外情况

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

上述就是C#学习教程:在任务中抛出exception – “等待”与等待()分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/cdevelopment/1028231.html

(0)
上一篇 2022年1月10日
下一篇 2022年1月10日

精彩推荐