Basic Exception Handling in TPL

 25-Oct-2014   nityaprakash     TPL  Exception-Handling    Comments  0

When a task throw exception it cannot be catch into main method. In earlier cases (before TPL) we had to handle exception in same method which being executed in separate thread. Handling exception in thread is as necessary as in main application. It might cause application to misbehave or exit abruptly and corrupt the state/data of the application.

If the tasks are independent and exception is not handled properly task will stop executing without notifying to main thread but won't disrupt the other task executing in same Application domain.

If we want to handle exception in main thread than below is the basic way to handle this.


        static void Main(string[] args)
        {
            Task t1 = new Task(() =>
            {
                ArgumentNullException exception = new ArgumentNullException("param");
                exception.Source = "t1";
                throw exception;
            });

            Task t2 = new Task(() =>
            {
                throw new NullReferenceException { Source = "t2" };
            });

            Task t3 = new Task(() =>
            {
                Console.WriteLine("This is task 3");
            });

            t1.Start();
            t2.Start();
            t3.Start();
            try
            {
                Task.WaitAll(t1, t2, t3);
            }
            catch (AggregateException ex)
            {
                foreach (Exception e in ex.InnerExceptions)
                {
                    Console.WriteLine("source:{0} | Exception Type:{1}", e.Source, e.GetType());
                }
            }
            Console.WriteLine("Main method is completed.  Press enter to exit");
            Console.ReadLine();
        }


We can catch the exception on specific task when waiting for the task to complete or reading Result with Task.Result property when expecting result from task. In above code snippet, Task.Wait method where we are handling the exception which throws AggregateExcepton and list of exceptions for each task it is waiting for to complete. We can take appropriate action when we see specific type of exception.


Download Code
Nitya Prakash Sharma has over 10 years of experience in .NET technology. He is currently working as Senior Consultant in industry. He is always keen to learn new things in Technology and eager to apply wherever is possible. He is also has interest in Photography, sketching and painting.

My Blog
Post Comment

COMMENTS