Getting a .Net application to close on crash
I have a开发者_如何学C .NET 4 app running on Windows Server 2008 R2 which I use a separate running process to manage its life cycle (i.e., detect turn on / unexpected shutdown / reboot). This works fine for typical conditions. However, when the application throws an exception, Windows brings up the debug window offering to debug the application. I just want the application to crash, so the process runner can detect the crash and manage accordingly.
How do I allow an application to close on an exception?
Add a handler to the Application.ThreadException
and in the handler, log the event, then exit nicely.
Also, add an event handler to AppDomain.CurrentDomain.UnhandledException as well.
Unhandled Exceptions MSDN
Edit: removed bit about Handled flag.. thanks Alex
Adding this line will prevent showing 'debug window'.
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);
You should add a global exception handler or a try/catch to clean up the resources, log the error and close the app normally.
精彩评论