11 June 2016

why and when windows service went down

If you have worked on developing Windows Service application, you might have thought about, is there any better way to know when and why a service went down unexpectedly. If that is your case, continue reading. This blog post aims to discuss one of the way, in which you can catch why and when windows service went down.

Whenever you start a .NET application, it runs in an AppDomain. You are free to create a new AppDomain depending on the need for your application. Windows service built on .NET(System.ServiceProcess.ServiceBase) also runs in an AppDomain. All the assemblies loading and unloading happens with a given AppDomain.

AppDomain object exposes an event called "UnhandledException". This event will be fired whenever there is an exception which is not handled in your application code.

One of the main reason why windows service unexpectedly goes down is because of an Exception which is not handled. If exceptions are not handled, then they traverse go up the stack trace and kill the process. When that happens, the current AppDomain event get notified before application goes down.

So, AppDomain's UnhandledException event can be used to get notified of any such unhandled exception.

Steps to get notified via AppDoman UnhandledException event

FIRST, subscribe to the UnhandledException event inside the Windows service Startup code. Do this as early as possible, so that you will also get notified of any exceptions happened even during service startup.