How can I execute some code when my process is going to exit? I've tried this:
public static void Main(string[] args) {
StartUpMyServer();
AppDomain.CurrentDomain.ProcessExit += delegate(object sender, EventArgs e)
{
Console.WriteLine("process exiting!");
TellMyServerToStopAcceptingConnectionsAndWaitUntilItsFinishedWithAnyExistingOnes();
};
Thread.Sleep(Timeout.Infinite);
}
"process exiting" is never printed and nothing else seems to happen.
Whatever it is, it needs to be cross-platform (Mono/Linux/OS X/Windows).
Thanks!
Clarification: I could probably accomplish what I want to do by starting and stopping the server on a separate thread and polling a 'stop requested' flag (which would be set in the ProcessExit event hander) on the main thread every X ms. I'd like to avoid this solution if possible (extra thread, cpu cycles). I just want to main thread to suspend until such time as the process is exiting, when it should tell the server to stop. Possible?