In .NET, is there a method, such as an event, for detecting when a Console Application is exiting? I need to clean up some threads and COM objects.
I am running a message loop, without a form, from the console application. A DCOM component that I am using seems to require that the application pump messages.
I have tried adding a handler to Process.GetCurrentProcess.Exited and Process.GetCurrentProcess.Disposed.
I have also tried adding a handler to Application.ApplicationExit and Application.ThreadExit events, but they are not firing. Perhaps that is because I am not using a form.
You can use the
ProcessExit
event of theAppDomain
:Update
Here is a full example program with an empty "message pump" running on a separate thread, that allows the user to input a quit command in the console to close down the application gracefully. After the loop in MessagePump you will probably want to clean up resources used by the thread in a nice manner. It's better to do that there than in ProcessExit for several reasons:
Here is the code:
For the CTRL+C case, you can use this:
Here is a complete, very simple .Net solution that works in all versions of windows. Simply paste it into a new project, run it and try CTRL-C to view how it handles it:
The application is a server which simply runs until the system shuts down or it receives a Ctrl+C or the console window is closed.
Due to the extraordinary nature of the application, it is not feasible to "gracefully" exit. (It may be that I could code another application which would send a "server shutdown" message but that would be overkill for one application and still insufficient for certain circumstances like when the server (Actual OS) is actually shutting down.)
Because of these circumstances I added a "ConsoleCtrlHandler" where I stop my threads and clean up my COM objects etc...
This setup seems to work out perfectly. Here is a link to some C# code for the same thing.
If you are using a console application and you are pumping messages, can't you use the WM_QUIT message?
As a good example may be worth it to navigate to this project and see how to handle exiting processes grammatically or in this snippet from VM found in here