I am writing a C# console application and am trying to check when my main program’s process has exited, so that I can do some cleanup before exiting, but the event never seems to fire. Here is the code to set the event handler:
Process process = Process.GetCurrentProcess();
CloseConsoleHandler close = new CloseConsoleHandler(test);
process.EnableRaisingEvents = true;
process.Exited += close.CloseHandler;
//I also tried process.Exited += new EventHandler(close.CloseHandler);
It just never seems to fire, not when the program ends naturally, not when I click the close button… never. Is this even possible?
Process exited event should logically fire AFTER a process exits, so therefore it’s impossible to catch it’s own exit.
But there are other alternatives, like implementing Dispose in your class to do cleanup, or for some reason you need the Process exited event, just monitor the process from another process.