Luke
Luke

Reputation: 2486

C# - Is it possible to catch a <Process>.Exited event fired from the main process?

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?

Upvotes: 10

Views: 15858

Answers (7)

nico
nico

Reputation: 21

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!");
    }
}

Upvotes: 2

for_example
for_example

Reputation: 39

Use

        Process p = new Process();
        p.EnableRaisingEvents = true;

Upvotes: 3

Csaba Toth
Csaba Toth

Reputation: 10697

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.

Upvotes: 1

Yahia
Yahia

Reputation: 70369

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).

Upvotes: 0

elevener
elevener

Reputation: 1097

Process.Exit is called only for associated processes and after termination. Try using ProcessExit event of current AppDomain.

Upvotes: 1

Can Poyrazoğlu
Can Poyrazoğlu

Reputation: 34780

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.

Upvotes: 7

SLaks
SLaks

Reputation: 887285

That won't work; once the process has ended, your code is gone.

Handle the AppDomain.ProcessExit event.

Upvotes: 9

Related Questions