Another important aspect of TPL is working with exceptions. Just as the normal code that we write can generate an exception, so can the code inside a TPL task. Since every task has its own stack, we cannot work with exceptions in the usual way. TPL has several options that allow us to work with exceptions in a parallel program.
The easiest option is to check the task status. If an exception has been raised inside the task, it will have the Status
property set to TaskStatus.Faulted
. The exception will be available through the Task.Exception
property:
var task = Task.Factory.StartNew(() => { throw new ApplicationException("Test exception"); }); while (!task.IsCompleted) {} Console.WriteLine("Status = {0}", task.Status); Console.WriteLine(task.Exception);
This code prints the following:
Status = Faulted System.AggregateException: One or more errors occurred. ---> System.ApplicationException: Test exception ...
The original exception that has been thrown in the code...