Exception handling in the .NET Task Parallel Library with C#: the basics
February 11, 2014 5 Comments
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.
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).
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 😉
Pingback: ¿Cómo manejar la excepción Task.Factory.StartNew? C#
Pingback: Как обрабатывать исключение Task.Factory.StartNew? Flip C#