Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle all unhandled exceptions when using Task Parallel Library?

I'm using the TPL (Task Parallel Library) in .NET 4.0. I want to centralize the handling logic of all unhandled exceptions by using the Thread.GetDomain().UnhandledException event. However, in my application, the event is never fired for threads started with TPL code, e.g. Task.Factory.StartNew(...). The event is indeed fired if I use something like new Thread(threadStart).Start().

This MSDN article suggests to use Task.Wait() to catch the AggregateException when working with TPL, but that is not what I want because this mechanism is not "centralized" enough.

Does anyone experience same problem at all or is it just me? Do you have any solution for this?

like image 793
Buu Nguyen Avatar asked Apr 25 '10 05:04

Buu Nguyen


People also ask

How do you handle exceptions in parallel ForEach?

For and Parallel. ForEach overloads do not have any special mechanism to handle exceptions that might be thrown. In this respect, they resemble regular for and foreach loops ( For and For Each in Visual Basic); an unhandled exception causes the loop to terminate as soon as all currently running iterations finish.

How do you handle exceptions thrown by tasks?

Exceptions are propagated when you use one of the static or instance Task. Wait methods, and you handle them by enclosing the call in a try / catch statement. If a task is the parent of attached child tasks, or if you are waiting on multiple tasks, multiple exceptions could be thrown.

What happens if a task throws an exception?

If Bar throws an exception, it will be thrown right at the point where you call it. However, if the Task that Bar returns wraps an exception, what happens depends on your version of . NET runtime - for .

How do you prevent AggregateException?

To avoid having to iterate over nested AggregateException exceptions, you can use the Flatten method to remove all the nested AggregateException exceptions, so that the InnerExceptions property of the returned AggregateException object contains the original exceptions.


1 Answers

I think TaskScheduler.UnobservedTaskException Event is what you want:

Occurs when a faulted Task's unobserved exception is about to trigger exception escalation policy, which, by default, would terminate the process.

So, this event is similar to DomainUnhandledException that you mentioned in your question but occurs only for tasks.

BTW note, that unobserved-exceptions policy (yeah, this is not an unobserved exceptions, MS guys invented new word ... again), changed from .NET 4.0 to .NET 4.5. In .NET 4.0 unobserved exception leads to process termination but in .NET 4.5 - don't. This is all because new async stuff that we'll have in C# 5 and VB 11.

like image 142
Sergey Teplyakov Avatar answered Oct 09 '22 16:10

Sergey Teplyakov