Home > Development > Task Parallel Library Tasks and Exceptions

Task Parallel Library Tasks and Exceptions


Lets look at some basic code then describe then functionality.

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

namespace ExceptionExamples
{
    class Program
    {
        static void Main(string[] args)
        {

            try
            {

                Task t1 = Task.Factory.StartNew(() =>
                {
                    throw new InvalidOperationException("Error In Code Snippet 1....");
                });

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


                t2.Wait(); // Exception will be rethrown up
            }
            catch (AggregateException ex)
            {
                foreach (Exception exception in ex.InnerExceptions)
                {

                    var invalidexception = exception as InvalidOperationException;
                    if (invalidexception != null)
                        Console.WriteLine("Type of Exception: {0}, Message: {1}", typeof(InvalidOperationException).FullName, invalidexception.Message);
                }
            }

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

If you do not catch exceptions in your task action method they bubble up. This only causes issues if you call a method on the task after like .Wait() etc though. So the only message that prints out is the message from task 2.

Exceptions could happen in multiple tasks so the are wrapped in an AggregateException and you can access all of the exceptions using the InnerExceptions property and take appropriate actions.

Blair…

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: