来自:http://www.codebrothers.net/mdenkmaier/archive/how-to-catch-unhandledexception-in-windows-services/BlogEntry.aspx
From time to time you will have to implement some functionality as an Windows service.
Along with some other issues regarding to Windows services you often get some troubles when unhandled exceptions occur. Specially in multi threaded services error situations sometimes only occur under specific circumstances and it is really hard to test for all possibilities.
In the .NET Framework 1.0 and 1.1 the framework handled nearly every exception silently that occuredin a worker thread by just catching them and cleaning up the mess. Therefore it could happen that your service died step by step without throwing an error. This includes manually created threads, thread pool threads and the CLRs finalizer threads.
Things have changed in the .NET Framework 2.0. In 2.0 the framework will terminate the whole process including all threads running in the same process bounderies.
There is no possibility to stop the termination process but you can react on it by attaching some code to the UnhandledException event handler of the AppDomain your process is running in:
AppDomain
.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler( CurrentDomain_UnhandledException );
void
CurrentDomain_UnhandledException( object sender, UnhandledExceptionEventArgs e ){//And then log the error and cleanup your stuff}Your process will be terminated anyway so just take careto prepare a clean shutdown of your service.
Note: The best placeI can think of for attaching to the handler would be in the constructor of your service class.
Thereare some other things to notice about service exceptions especially regarding to the event log entries generated by the framework:
1. If you do not attach code to the eventhandler and you are not logged on to the system when your service fails you will only see an SystemEventLog entry with the source set to .NET Runtime 2.0 Error Report and the description to something like: EventType clr20r3, P1... P2... P3...
2. You are not logged on to the maschine when the exception occurs and you use the UnhandledException event handler:
The framework creates an SystemEventLog entry as described under 1.
The framework (or better theJITDebugger VsJITDebugger)also will log the exception to the SystemEventLog with a message like that: Unhandled Exception (xyz) in abc. The debugger could not be started, because there was no user logged on!
3. As long as you are logged on to the maschine while the service exception occurs and you use the UnhandledException event handler:
You will see the well known JITDebugger Dialog popping up asking you what you want to do.
The framework logs the exception to the SystemEventLog with a message like that: The service abc was terminated unexpected. This happened already x times!
I hope this helps some of you trouble shooting Windows service problems.