Is it possible to catch when any Task terminates due exception and log? I’ve added CurrentDomain_UnhandledException handling but this doesn’t help.
I create tasks using Task.Factory.StartNew() as usual. When somewhere inside such task exception occurs it crashes silently (but it supposed to work forever, i’m also using LongRunning option). So I want to be notified about such behavior.
Ideallly I want to set some option somewhere to be notified when any Task crashes due exception.
If it is not possible then likely I should add something to each Task I create? Of course I can just add big try{} finally{} block inside each Task, but probably there are better solutions?
For tasks that you create yourself, it’s reasonably simple: create your own methods which call
Task.Factory.StartNew(), but then also callTask.ContinueWith(loggingDelegate, TaskContinuationOptions.OnlyOnFaultedbefore returning the task.The problem is that that won’t add a fault handler for tasks created by other bits of infrastructure – including by async methods in C# 5. It still might be useful to you though.
You can also use
TaskScheduler.UnobservedTaskException, but as per the name that will only be called for exceptions which aren’t already observed by something else. (Again, that may be fine for you…)