Before reading this article I request that you read my previous article on Parallel Task that is a feature in .Net 4.0 so that you can get a better idea regarding Exception Handling in tasks.
I am writing this article as requested by one of my friends on C# corner. When I talked regarding the parallel execution of tasks in my previous article, I didn't explain exception handling. I mean in parallel task execution, exception handling is important and behaves in a different manner.
Let us continue with the same example that I used in my earlier article of "A person digging in the ground". We knew that unhandled exceptions that are thrown by user code need to be handled.
Let's consider the scenario and understand exception handling for it.
1. Exception handling for Single Task
Now, a person while digging the ground suddenly the tool got crashed and he must stop the further digging. Now it's easy to handle this kind of exception.
- Task t = Task.Factory.StartNew(() => {
- try
- {
- Console.WriteLine("Digging is in progress");
- throw new Exception("Tool is crashed");
- }
- catch (Exception ae)
- {
- Console.WriteLine("Stop the work and notify others :" + ae.Message);
- } });
- t.Wait();
In the code snippet above, as you can find I have handled the exception simply using an Exception object.
2. Exception handling for Nested Task
The previous one was pretty simple, right? But it is not the right way of using it. I will explain later.
Now, what if one person wants to do some other small task along with digging that is going on, like removing the stones. Suddenly something went wrong. Another point is while digging too there was some problem with the tool too. Now what to do to handle both the exception that is running in parallel?
This task would be a child task for digging in the ground. Here there is a chance of getting exceptions in the Parent as well as the child task, in other words, multiple errors. And to propagate all the exceptions to the calling Thread, the Exception class is not capable of doing it. So the Task infrastructure wraps up all the exceptions into one object that is of type AggregateException. This is derived from the Exception class.

This class has an InnerExceptions property that can be enumerated to get all the exceptions while executing the Task and handling each of the Task exceptions differently. It can also be used to throw even a single Exception.
The figure above shows the Exception. You can see I have used an Exception object in the catch block to handle the Exception.







Vasanth KumarPosted May 10, 2018, 1:19 AM
Thank You Sir !!!!!
jegadeesh GRPosted May 4, 2017, 1:22 AM
Great ! thanks a lot
Anupam SinghPosted Jul 21, 2014, 10:34 AM
:) nicely described......