I have a Task which runs asynchronously and handles exceptions using a task continuation task.ContinueWith(t => ..., CancellationToken.None, TaskContinuationOptions.OnlyOnFaulted, taskScheduler).
This works great for handling exceptions I know how to handle (e.g. WebException), but what if something like NullReferenceException is thrown, which I can’t handle correctly?
I want to be able to handle it using the AppDomain’s unhandled exception handler (which in our case logs the error, pops up a dialog notifying the user, and exits the application), but so far I have not found a good way to do this.
Simply rethrowing the exception from the continuation results in the unhandled exception handler being called when the task is finalized (because the rethrown exception is unobserved). This is not good because it may be seconds or even minutes after I know the application should crash.
Calling Environment.FailFast() does crash the application but does not call the unhandled exception handler.
Calling Thread.CurrentThread.Abort() calls the unhandled exception handler but only displays information/the stack trace from the ThreadAbortException. Plus it just seems like a bad idea to use this method.
Calling Application.OnThreadException() actually does exactly what I want, except that it requires referencing System.Windows.Forms and handling Application.ThreadException which will not work with, for example, a service with no UI.
Calling task.Wait() does not make sense because this in our case there’s no place to call it from. If the task succeeds the result is processed using a success continuation, if it fails the exception continuation is called, and we can’t block the thread creating the task (that’s the whole point of the task).
I could call the unhandled exception handler directly except that in at least one case that would require adding a dependency I don’t want to add in my application.
Am I missing an obvious way to do this?
We used
Application.OnThreadException()to solve our specific case.