protected override void OnStart(string[] args) { AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException); Thread.Sleep(10000); throw new Exception(); } void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) { }
I attached a debugger to the above code in my windows service, setting a breakpoint in CurrentDomain_UnhandledException, but it was never hit. The exception pops up saying that it is unhandled, and then the service stops. I even tried putting some code in the event handler, in case it was getting optimized away.
Is this not the proper way to set up unhandled exception handling in a windows service?
An ExceptionFilterAttribute is used to collect unhandled exceptions. You can register it as a global filter, and it will function as a global exception handler. Another option is to use a custom middleware designed to do nothing but catch unhandled exceptions.
Use the Server object's GetLastError method to retrieve details of the unhandled exception that caused the Error event to fire. The GetLastError method returns an object of type Exception , which is the base type for all exceptions in the . NET Framework.
If you don't have any means of catching or trapping exceptions then they become unhandled and will cause program failure. Major errors can occur if your code divides by zero or tries to reference a value that doesn't exist.
The reason that the UnhandledException
event on the current AppDomain does not fire is how services are executed.
ServiceBase
implementation and dispatched to the OnStart
method.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With