[英]C# InnerException in AggregateException
I have this code as below to capture the exceptions throw from tasks created by using TaskFactory and Task.Run.我有如下代码来捕获从使用 TaskFactory 和 Task.Run 创建的任务抛出的异常。 If I use the TaskFactory, I am able to check the Exception thrown from the previous task in the Continued task without having to use the Task.WaitAll method.如果我使用 TaskFactory,我可以检查从 Continued 任务中的前一个任务抛出的异常,而无需使用 Task.WaitAll 方法。 If I use Task.Run, the Continued task will not execute unless I explicitly Wait for the child tasks to finish.如果我使用 Task.Run,除非我明确等待子任务完成,否则将不会执行 Continued 任务。 Which flag in the TaskFactory.StartNew changed this behaviour? TaskFactory.StartNew 中的哪个标志改变了这种行为?
Also what is the difference between InnerException and InnerExceptions in AggregateException class? AggregateException 类中的 InnerException 和 InnerExceptions 之间有什么区别? The InnerExceptions returns me a readonly collection of all exceptions thrown by the child tasks. InnerExceptions 向我返回子任务抛出的所有异常的只读集合。 The InnerException returns an AggregateExcpetion of exception thrown by only one child task. InnerException 返回仅由一个子任务引发的异常的 AggregateExcpetion。
//Use Factory
TaskCreationOptions atp = TaskCreationOptions.AttachedToParent;
Task.Factory.StartNew(() =>
{
Task.Factory.StartNew (() => { throw null; }, atp);
Task.Factory.StartNew (() => { throw new NullReferenceException();}, atp);
Task.Factory.StartNew (() => { throw new Exception("Test"); }, atp);
})
.ContinueWith (p => p.Exception.Dump(),TaskContinuationOptions.OnlyOnFaulted);
//Use Task.Run
Task.Run(()=>
{
TaskCreationOptions op = TaskCreationOptions.AttachedToParent;
var t1 = Task.Factory.StartNew(()=> {throw null;}, op);
var t2 = Task.Factory.StartNew(()=> {throw new NullReferenceException();}, op);
var t3 = Task.Factory.StartNew(()=> {throw new Exception("Test");}, op);
//This will trigger the continued task
//Task.WaitAll(new Task[]{t1,t2,t3});
}).ContinueWith(task => {task.Exception.Dump();}, TaskContinuationOptions.OnlyOnFaulted);
InnerException
is a property of Exception
with returns 'the exception that caused this exception' . InnerException
是Exception
一个属性,返回'导致此异常的异常' 。InnerExceptions
is a property unique to AggregateException
. InnerExceptions
是AggregateException
独有的属性。 Due to its design, an aggregate exception can contain multiple 'causing' exceptions.由于其设计,聚合异常可以包含多个“导致”异常。 As the property InnerException
is inherited, it makes sense that it returns the first exception from InnerExceptions
.由于属性InnerException
是继承的,因此它从InnerExceptions
返回第一个异常是有意义的。
To answer your other question re the behaviour of your sample code, the difference is the TaskCreationOptions
default for Task.Run
.要回答再你的示例代码的行为,您的其他问题,所不同的是TaskCreationOptions
默认Task.Run
。 The default is TaskCreationOptions.DenyChildAttach
.默认值为TaskCreationOptions.DenyChildAttach
。 You can read more about that in this blog post .您可以在这篇博文中阅读更多相关信息。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.