ExceptionHandler–How to prevent crashes from background threads?

Posted on November 28, 2010 by

0


ExceptionHandler is called when an exception is thrown from WCF on a background asynchronous thread.

Such exceptions can be handled by a custom exception handler, that should be specified in the following way:

ExceptionHandler.
        AsynchronousThreadExceptionHandler
             = new MyExceptionHandler();

See MSDN documentation on AsynchronousThreadExceptionHandler

The default ExceptionHandler always returns false, which triggers the UnhandledException event and causes the  AppDomain to crash.

Note:

Returning true from the ExceptionHandler will prevent the application from crashing. Note that it can also mean that the application is in unstable condition.

Sample Exception Handler

In the following example we instruct the application to swallow CommunicationException thrown from background threads, and to crash on all other received exceptions.

    internal class MyExceptionHandler : ExceptionHandler
    {
        public override bool HandleException(Exception exception)
        {
            Type exceptionType = exception.GetType();
            if (typeof(CommunicationException).IsAssignableFrom(exceptionType))
            {
                Console.WriteLine(String.Format(
                "NOT terminating the process after receiving the following exception: '{0}'", exception);
                return true;
            }
            return false;
        }
    }

Advertisements
Posted in: WCF Extensions