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?
Seems like there's no built-in way to handle this (and no answer to this question after almost 2 weeks). I already rolled out some custom code to take care of this. The solution description is pretty lengthy, so I've posted in my blog. Refer to this post if you're interested.
Update 5/7/2010: I’ve found a better way to do that, making use of task continuation. I create a class ThreadFactory
that exposes the Error event which can be subscribed by a top-level handler and provides methods to start a task attached with proper continuation.
The code is posted here.
Update 4/18/2011: Post code from the blog post as per Nifle's comment.
internal class ThreadFactory
{
public delegate void TaskError(Task task, Exception error);
public static readonly ThreadFactory Instance = new ThreadFactory();
private ThreadFactory() {}
public event TaskError Error;
public void InvokeError(Task task, Exception error)
{
TaskError handler = Error;
if (handler != null) handler(task, error);
}
public void Start(Action action)
{
var task = new Task(action);
Start(task);
}
public void Start(Action action, TaskCreationOptions options)
{
var task = new Task(action, options);
Start(task);
}
private void Start(Task task)
{
task.ContinueWith(t => InvokeError(t, t.Exception.InnerException),
TaskContinuationOptions.OnlyOnFaulted |
TaskContinuationOptions.ExecuteSynchronously);
task.Start();
}
}