Home > Development > Task Parallel Library – Handling Exceptions Part 2

Task Parallel Library – Handling Exceptions Part 2


When using the task parallel library you can decided to handle exceptions or to bubble then up the call stack by handling or not handling the exception. Lets look at 2 examples of the same code with one line changed to illustrate.

Example 1

using System;
using System.Threading.Tasks;
using System.Threading;

namespace TPLTasks
{
    class Program
    {
        static void Main()
        {
            try
            {
                RunTasks();
            }
            catch (AggregateException)
            {
                Console.WriteLine("Caught the exception in Main");
            }

            Console.WriteLine("Press any key to quit..");
            Console.ReadKey();
        }

        static void RunTasks()
        {
            try
            {

                CancellationTokenSource source = new CancellationTokenSource();
                CancellationToken token = source.Token;

                Task t1 = Task.Factory.StartNew(token.ThrowIfCancellationRequested, token);

                Task t2 = Task.Factory.StartNew(() =>
                {
                    throw new InvalidOperationException("Error In Code Snippet 2....");
                }, token);

                t2.Wait(); // Exception will be rethrown up
            }
            catch (AggregateException ex)
            {
                ex.Handle(
                    exp =>
                        {
                            if (exp is OperationCanceledException)
                            {
                                Console.WriteLine("Handled Cancelled");
                                return true;
                            }
                            return false;
                        }
                    );
            }
        }
    }
}

In this example we never cancel the token so an exception is never thrown from task 1. However task 2 throws an exception. In the catch block in the current method we are only stating we want to handle exceptions of type Operation cancelled exception as it return true indicating its something we care about, everything else returns false. Thus it is handled in the main methods exception catch block.

Example 2

using System;
using System.Threading.Tasks;
using System.Threading;

namespace TPLTasks
{
    class Program
    {
        static void Main()
        {
            try
            {
                RunTasks();
            }
            catch (AggregateException)
            {
                Console.WriteLine("Caught the exception in Main");
            }

            Console.WriteLine("Press any key to quit..");
            Console.ReadKey();
        }

        static void RunTasks()
        {
            try
            {

                CancellationTokenSource source = new CancellationTokenSource();
                CancellationToken token = source.Token;

                Task t1 = Task.Factory.StartNew(token.ThrowIfCancellationRequested, token);

                Task t2 = Task.Factory.StartNew(() =>
                {
                    throw new InvalidOperationException("Error In Code Snippet 2....");
                }, token);

                source.Cancel();
                t2.Wait(); // Exception will be rethrown up
            }
            catch (AggregateException ex)
            {
                ex.Handle(
                    exp =>
                        {
                            if (exp is OperationCanceledException)
                            {
                                Console.WriteLine("Handled Cancelled");
                                return true;
                            }
                            return false;
                        }
                    );
            }
        }
    }
}

In this example cancel the token so an exception is thrown from task 1.. In the catch block in the current method we are only stating we want to handle exceptions of type Operation cancelled exception as it return true indicating its something we care about, everything else returns false. Thus it is handled in this block and not bubbled up.

Advertisements
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: