Exception handling in Task Parallel Library


Handling Exceptions in parallel world is always challenge. If you know exceptions can be raised from piece of code then you wrap in try catch block to handle managed exceptions. But sometimes unhandled exceptions can be raised. It is very dangerous to not handle unhandled exceptions because it can stop execution of code unpredictably. Task Parallel Library (TPL)  provides consistent way of handling unhandled exceptions that raised while executing tasks in parallel.

If any exception occur in parallel task then CLR raise AggregateException object but this exception will not be caught until you trigger Wait, WaitAll, WaitAny methods of task class. You can see in below code, parallel loop fires exception but it doesn’t catch in catch block.

	public void Execution()
        {
            try
            {

                var task1 = Task.Factory.StartNew(() =>
                            {

                                for (int i = 0; i < 100; i++)
                                {
                                    if (i == 20)
                                        throw new Exception("throwing unhandled exception");
                                }

                            }
                );

            }
            catch (AggregateException ex)
            {
                foreach (Exception innerEx in ex.InnerExceptions)
                    Console.WriteLine(innerEx.Message);

            }

        }

Output

Please Key to Execute Tasks

SimpleCancelTask : 1

CancelSeveralTasks : 2

MonitorTaskwithDelegates : 3

Exception Handling : 4

4Executing Exception Handling Samples

Press enter to exit

To catch exception you need to put task1.Wait() method. AggregateException object wraps all exceptions raised in parallel tasks in inner exception collections.

public void Execution()
        {
            try
            {

                var task1 = Task.Factory.StartNew(() =>
                            {

                                for (int i = 0; i < 100; i++)
                                {
                                    if (i == 20)
                                        throw new Exception("throwing unhandled exception");
                                }

                            }
                );

                task1.Wait();
            }
            catch (AggregateException ex)
            {
                foreach (Exception innerEx in ex.InnerExceptions)
                    Console.WriteLine(innerEx.Message);

            }

        }

Output

Please Key to Execute Tasks

SimpleCancelTask : 1

CancelSeveralTasks : 2

MonitorTaskwithDelegates : 3

Exception Handling : 4

4Executing Exception Handling Samples

throwing unhandled exception

Press enter to exit

In above output you can see exception has caught and showing exception message as inner exception.

Now I will discuss how we can capture exceptions when triggered from many parallel tasks.

Exceptions Handling in many parallel tasks

You can trigger AggregatedException object from different parallel tasks by putting Task.WaitAll method which will wait for all tasks exceptions.

public void ExecutionHandlingForManyTasks()
        {
            try
            {
                Console.WriteLine("Output");
                Console.WriteLine("============================================================");
                Console.WriteLine("\n\n");
                var task1 = Task.Factory.StartNew(() =>
                {

                    for (int i = 0; i < 100; i++)
                    {
                        if (i == 20)
                            throw new Exception("Task1: throwing unhandled exception");
                    }

                }
                );

                var task2 = Task.Factory.StartNew(() =>
                {
                    throw new Exception("Task2: throwing unhandled exception");
                }
                );

                Task.WaitAll(task1, task2);

            }
            catch (AggregateException ex)
            {
                foreach (Exception innerEx in ex.InnerExceptions)
                    Console.WriteLine(innerEx.Message);

            }

        }

Output

Please Key to Execute Tasks

SimpleCancelTask : 1

CancelSeveralTasks : 2

MonitorTaskwithDelegates : 3

Exception Handling in one task: 4

Exception Handling in many tasks: 5

5Output

============================================================

Task2: throwing unhandled exception

Task1: throwing unhandled exception

Press enter to exit

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Powered by WordPress.com.

Up ↑

%d bloggers like this: