Global handling exception in window service
I have a windows service run as a serve开发者_JS百科r. However, the server sometime stops immediately by an error which is un-handled. Please help me how to handle global exception. Thanks.
It sounds to me like you're trying to solve the problem the wrong way around...
When your program (or service) crashes because of an unhandled error, the solution is not to figure out where and how to "handle" all unhandled errors so that you can ignore them and continue execution. I've hashed out that view more clearly in this answer, but the short version is that when you encounter an unhandled exception, the correct thing to do is to crash. As quoted in the original answer:
The fact that an unhandled exception occurred means that the server was in an unexpected state. By catching the exception and saying, "Don't worry, it's all good," you end up leaving a corrupted server running.
[ . . . ]
Catching all exceptions and letting the process continue running assumes that a server can recover from an unexpected failure. But this is absurd. You already know that the server is unrecoverably toast: It crashed!
Much better is to let the server crash so that the crash dump can be captured at the point of the failure. Now you have a fighting chance of figuring out what's going on.
So in fact, the real solution involves figuring out the root cause of the unhandled exception and modifying your code to prevent that error from occurring in the first place.
There's no way that we can help you to do that unless you post the exact exception message that you're getting, and preferably a full stack trace. But you definitely want to preserve the debugging information that you're getting, rather than come up with a way to ignore it entirely—that's the only way to actually solve the problem.
If you still insist on ignoring all well-meaning advice to the contrary, you'll find the "stick your head in the sand and ignore it" approach detailed here.
You could try using the AppDomain.CurrentDomain.UnhandledException
event, although I'm not sure if it will catch every single unhandled exception.
精彩评论