I am writing a C# console application and am trying to check when my main program's process has exite开发者_如何转开发d, 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?
That won't work; once the process has ended, your code is gone.
Handle the AppDomain.ProcessExit
event.
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.
Use
Process p = new Process();
p.EnableRaisingEvents = true;
Process.Exit is called only for associated processes and after termination. Try using ProcessExit event of current AppDomain.
Or you can try to solve that at application level if you own the main app too (it sounds like): signal the child process from the main app with some technique when the main app is closing. Maybe I'd try to signal synchronously this time, so the main app leaves time for the child for cleanup. This approach has it's own drawbacks though. The ideal would be to catch some system event at your child process.
You can add a custom handler to the ProcessExit event and do your cleanup there. For example:
class Program
{
static void Main(string[] args)
{
// Register hanlder to ProcessExit event
AppDomain.CurrentDomain.ProcessExit += ProcessExitHanlder;
}
private static void ProcessExitHanlder(object sender, EventArgs e)
{
Console.WriteLine("Cleanup!");
}
}
AFAIK there are two ways - depending on your preference one P/Invoke way (see http://osdir.com/ml/windows.devel.dotnet.clr/2003-11/msg00214.html )... this calls a delegate you define in a separate thread upon Exit of your app and works with console...
The other way is AppDomain.ProcessExit
- which has a time limit it is allowed to run (default 3 seconds).
精彩评论