I have a question regarding the .NET Task Parallel Library's error handling. In which cases will an AggregateException
hold more than 1 inner exception? I know this can happen for ex. when calling Task.WaitAll(anArrayOfTasks)
, and 2 or more tasks are throwing an exception, but are there any other cases (i.e., can it be possible that, if only waiting for 1 task to finish, you get more than 1 inner exceptions)?
Exception. An object that describes the error that caused the current exception. The InnerException property returns the same value as was passed into the Exception(String, Exception) constructor, or null if the inner exception value was not supplied to the constructor. This property is read-only.
AggregateException is used to consolidate multiple failures into a single, throwable exception object. It is used extensively in the Task Parallel Library (TPL) and Parallel LINQ (PLINQ). For more information, see Exception Handling and How to: Handle Exceptions in a PLINQ Query.
The InnerException is a property of an exception. When there are series of exceptions, the most current exception can obtain the prior exception in the InnerException property. Let us say we have an exception inside a try block throwing an ArgumentException and the catch clause catches it and writes it to a file.
Flattens an AggregateException instances into a single, new instance.
A task can raise an aggregate exception which inherently can contain multiple inner exceptions. This means that you should always consider an aggregate exception with multiple inner exceptions when working with tasks. Even if you're not using Task.WaitAll, the task you're waiting on might internally wait for multiple subtasks. Alternatively, the task your waiting on might return multiple exceptions. You simply can't know as a caller.
This can happen if you have a “parent” task and one or more “child” tasks that are attached to the parent. What that means is that the parent task will finish only when all of its child tasks finish and the exceptions from child tasks are also propagated to the parent task.
Take, for example, the following code:
var task = Task.Factory.StartNew(
() =>
{
Task.Factory.StartNew(
() => { throw new Exception("inner"); },
TaskCreationOptions.AttachedToParent);
throw new Exception("outer");
});
If you Wait()
on that task, it thows an AggregateException
, that looks like this:
AggregateException
Exception
: outerAggregateException
Exception
: innerIf you don't like that it can contain AggregateException
s inside AggregateException
s, you can use the Flatten()
method. There's also another method that can be used for processing of AggregateException
s: Handle()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With