user1439090 user1439090 - 2 months ago 12
C# Question

How to check when an exe application ends?

I am creating an application in C# which calls a batch file, then executes another .net exe file and then runs another batch file when the exe file is closed.

I can run the initial batch file and I can call the exe file using the

method but how can I check when the exe file is finally terminated so that I can run the final batch file?


You can either call WaitForExit():


When an associated process exits (that is, when it is shut down by the operation system through a normal or abnormal termination), the system stores administrative information about the process and returns to the component that had called WaitForExit(). The Process component can then access the information, which includes the ExitTime, by using the Handle to the exited process.

Or, enable events and hook code on the exited event:

myProcess.EnableRaisingEvents = true;
myProcess.Exited += new EventHandler(myProcess_Exited);


private void myProcess_Exited(object sender, System.EventArgs e)
    Console.WriteLine("Exit time:    {0}\r\n" +
        "Exit code:    {1}\r\nElapsed time: {2}", myProcess.ExitTime, myProcess.ExitCode, elapsedTime);

The key difference is synchronous or asynchronous. From the exited docs:

There are two ways of being notified when the associated process exits: synchronously and asynchronously. Synchronous notification relies on calling the WaitForExit method to pause the processing of your application until the associated component exits. Asynchronous notification relies on the Exited event. In either case, EnableRaisingEvents must be set to true for the Process component to receive notification that the process has exited.

Also, when you get to running batch file, check out this post:

How to execute a batch file from C#?