Exception handling in the .NET Task Parallel Library with C#: the basics

Handling exceptions in threading is essential. Unhandled exceptions can cause your application to exit in an unexpected and unpredictable way.

If a task throws an exception that’s not caught within the task body then the exception remains hidden at first. It bubbles up again when a trigger method is called, such as Task.Wait, Task.WaitAll, etc. The exception will then be wrapped in an AggregateException object which has an InnerException property. This inner exception will hold the actual type of exception thrown by the tasks that are waited on.

Construct and start the tasks:

Task firstTask = Task.Factory.StartNew(() =>
{
	ArgumentNullException exception = new ArgumentNullException();
	exception.Source = "First task";
	throw exception;
});
Task secondTask = Task.Factory.StartNew(() =>
{
	throw new ArgumentException();
});
Task thirdTask = Task.Factory.StartNew(() =>
{
	Console.WriteLine("Hello from the third task.");
});

Wait for all the tasks, catch the aggregate exception and analyse its inner exceptions:

try
{
	Task.WaitAll(firstTask, secondTask, thirdTask);
}
catch (AggregateException ex)
{
	foreach (Exception inner in ex.InnerExceptions)
	{
		Console.WriteLine("Exception type {0} from {1}",
			inner.GetType(), inner.Source);
	}
}

Note: if you run the above code in Debug mode in a console application then the execution will stop at each exception thrown. To simulate what’s going to happen in a deployed application make sure you run the code without debugging (Ctlr + F5).

View the list of posts on the Task Parallel Library here.

Advertisement

About Andras Nemes
I'm a .NET/Java developer living and working in Stockholm, Sweden.

5 Responses to Exception handling in the .NET Task Parallel Library with C#: the basics

  1. Or you can check e.g. firstTask.IsFaulted. When set to true, u can get the exceptions from firstTask.Exception (It’s an AggregateException, too).

    • Andras Nemes says:

      Hallo Stefan,

      Thanks for your input.

      //Andras
      PS: ich sehe dass du mit deinem Blog angefangen hast. Wann kommt der erste Beitrag? Hast du vor auf Deutsch oder English zu schreiben?

      • Ich habe vor den in der nächsten Woche zu schreiben. Thema hab ich schon im Kopf 🙂
        Vorläufig werde ich auf Deutsch schreiben. Vielleicht später mal auf Englisch.
        LG Stefan

        Ps: Wenn du mir auf Twitter folgst, kann ich dir auch meine Mail fürs einfachere schreiben geben 😉

  2. Pingback: ¿Cómo manejar la excepción Task.Factory.StartNew? C#

  3. Pingback: Как обрабатывать исключение Task.Factory.StartNew? Flip C#

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 )

Connecting to %s

Elliot Balynn's Blog

A directory of wonderful thoughts

Software Engineering

Web development

Disparate Opinions

Various tidbits

chsakell's Blog

WEB APPLICATION DEVELOPMENT TUTORIALS WITH OPEN-SOURCE PROJECTS

Once Upon a Camayoc

Bite-size insight on Cyber Security for the not too technical.

%d bloggers like this: