How can I set up .NET UnhandledException handling in a Windows service?

Solution 1:

The reason that the UnhandledException event on the current AppDomain does not fire is how services are executed.

  1. User sends a Start command from the Windows Service Control Manager (SCM).
  2. The command is received by the framework's ServiceBase implementation and dispatched to the OnStart method.
  3. The OnStart method is called.

Any exception which is thrown by OnStart is handled in the base class, logged to the Event Log, and translated into an error status code returned to the SCM. So the exception never propagates to the AppDomain's unhandled exception handler.

I think you would find that an unhandled exception thrown from a worker thread in your service would be caught by the AppDomain's unhandled exception handler.

Solution 2:

In a Windows Service you do NOT want to be running much code in the OnStart method. All you want there is the code to launch your service thread and then return.

If you do that you can handle exceptions that happen in your service thread just fine.

e.g.

public static void Start()
{
    AppDomain currentDomain = AppDomain.CurrentDomain;
    currentDomain.UnhandledException += new UnhandledExceptionEventHandler(currentDomain_UnhandledException);

    running = true;
    ThreadStart ts = new ThreadStart(ServiceThreadBody);
    thread = new Thread(ts);
    thread.Name = "ServiceThread";
    thread.Priority = ThreadPriority.BelowNormal;
    thread.Start();
}