Resolve WCF Service problem with Unhandled Exception

Background

In one of my project recently I faced a problem where in a WCF service would encounter an exception and would stop working. The exception was related to the caching mechanism. We were trying to access some data from the web server cache using the ASP.Net cache API. There was a callback method used to repopulate the cached item when it expired after a certain interval.
If the item was forcefully removed from the cache it would result in an exception when the next call was made to access the value of the cached key.

Handle Exceptions to avoid AppDomain from shutting down

During development testing the cached item never got removed forcefully and we did not encounter this problem. But during integration testing it surfaced.
Today i was reading some stuff on Threading in C# and came across a point made by the author, Joseph Albahari. This is what he had to say “From .NET 2.0 onwards, an unhandled exception on any thread shuts down the whole application, meaning ignoring the exception is generally not an option. Hence a try/catch block is required in every thread entry method – at least in production applications – in order to avoid unwanted application shutdown in case of an unhandled exception.
We tried couple of ways earlier to understand the reason why the service was failing after logging the exception. The reason our service was failing because we were catching the exception in the catch block and logging it to the log file. We were also throwing the exception back which resulted in it being treated as an unhandled exception.

Conclusion

From .Net 2.0 onwards we cannot ignore exception. Every entry method on the Thread should have try catch block to avoid unhandled exceptions and thus shutting down the AppDomain which can bring down your application instantly. Although unintentional, I discovered something new while reading about threading that helped me resolve a problem in an existing problem.  Hope this might be helpful to someone else as well.
Until next time Happy Programming  :)
spacer