How to prevent an exception in a background thread from terminating an application?

First, you really should try not to have exceptions thrown – and not handled – in a background thread. If you control the way your delegate is run, encapsulate it in a try catch block and figure a way to pass the exception information back to your main thread (using EndInvoke if you explicitly called BeginInvoke, or by updating some shared state somewhere).

Ignoring a unhandled exception can be dangerous. If you have a real un-handlable exception (OutOfMemoryException comes into mind), there’s not much you can do anyway and your process is basically doomed.

Back to .Net 1.1, an unhandled exception in a backgroundthread would just be thrown to nowhere and the main thread would gladly plough on. And that could have nasty repercussions. So in .Net 2.0 this behavior has changed.

Now, an unhandled exception thrown in a thread which is not the main thread will terminate the process. You may be notified of this (by subscribing to the event on the AppDomain) but the process will die nonetheless.

Since this can be inconvenient (when you don’t know what will be run in the thread and you are not absolutely sure it’s properly guarded, and your main thread must be resilient), there’s a workaround. It’s intended as a legacy settings (meaning, it’s strongly suggested you make sure you don’t have stray threads) but you can force the former behavior this way :

Just add this setting to your service/application/whatever configuration file :

<configuration>
  <runtime>
    <!-- the following setting prevents the host from closing when an unhandled exception is thrown -->
    <legacyUnhandledExceptionPolicy enabled="1" />
  </runtime>
</configuration>

It doesn’t seem to work with ASP.NET, though.

For more information (and a huge warning that this setting may not be supported in upcoming versions of the CLR) see http://msdn.microsoft.com/en-us/library/ms228965.aspx

Leave a Comment