Exception handling

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); ...

Get Mastering C# Concurrency now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.