2
votes

Our WCF services occaisionally spawn a worker thread to handle something that the client doesn't care about. The worker threads do not report any status back to the client. In fact, the service has probably already returned results to the client by the time the thread finishes.

One of these background threads recently caused an exception. The exception went unhandled, so IIS crashed.

I can fix this particular exception, but in the future, someone may add some code that causes another unexpected exception. I want to prevent this from crashing IIS in the future.

I know System.Windows.Forms apps can handle thread exceptions by implementing Application.ThreadException. Is there something similar I can do from a WCF service? Or if Application.ThreadException is the way to go, how would I hook it up from a WCF service?

The MSDN documentation for AppDomain.UnhandledException says it does not prevent crashing. Docs for ServiceModel.AsynchronousThreadExceptionHandler suggest it is only for WCF threads.

At a minimum, I'd like to grab a stack trace from the exception before crashing, but avoid future crashes completely would be ideal.

Again, let me stress this is not an exception I want to return as a WCF fault to a client.

3

3 Answers

1
votes

Since you don't know what caused the exception, the only sensible thing to do is crash. You have no idea what state the service is in, and you could make things worse by continuing.

Remember that IIS will restart the service for you, clean, and presumably working.

1
votes

If you're spawning threads, you should always make sure they have exception guards. The AppDomain handling for unhandled exceptions only provides a way to log and trace the error, but it won't stop the host from crashing.

0
votes

You could take a look at implementing IErrorHandler with a Dispatch Behavior:

http://msdn.microsoft.com/en-us/library/system.servicemodel.dispatcher.ierrorhandler.aspx