I see two options which can be used for the purposes of centralization of exception handling in TPL:
1. Using of Unobserved Task Exception event of Task Scheduler.
2. Using of continuations for tasks with faulted state.
Using of Unobserved Task Exception event of Task Scheduler.
The task scheduler has an UnobservedTaskException event to which you can subscribe using operator +=.
- Note 1: In the body of handler you need to make call SetObserved() on UnobservedTaskExceptionEventArgs argument to notify scheduler that exception was handled.
- Note 2: The handler is called when the tasks have been collected by the garbage collector.
- Note 3: If you will wait on task you will still be forced to protect waiting by try/catch block.
- Note 4: The default policy for unhandled Task exceptions in .Net 4.0 and 4.5 is different.
Summary: This approach is good for fire-and-forget tasks and for catching of exceptions escaped from your centralized exception handling policy.
Using of continuations for tasks with faulted state.
With TPL you can attach actions to the Task using method ContinueWith() which takes attaching action and continuation option. This action will be called after the task termination and only in the cases specified by option. In particular:
t.ContinueWith(c => { /* exception handling code */ },
TaskContinuationOptions.OnlyOnFaulted);
installs continuation with exception handling code to the Task t. This code will be running only in the case when Task t was terminated due to the unhandled exception.
- Note 1: Get exception value in exception handling code. Otherwise it will be bubbled out.
- Note 2: Exception handling code will be called immediately after Task termination.
- Note 3: If the exception was got in exception handling code it will be considered as handled, try/catch block on task waiting will not be able to catch it.
I think that it will be better for centralized exception handling to use custom Tasks inherited from Task with exception handler added via continuation. And accompany this approach by using of Unobserved Task Exception event of Task Scheduler to catch attempts to use not customized tasks.