Roy Osherove

View Original

How To Know When An External Application Exits

I was asked how one can launch an external application and know when it is finished. Her'es the code (Console Application):

using System.Diagnostics;

 

static void Main(string[] args)

{

      Process p  = new Process();

 

      //Register for the event that notifies the process exit

      p.Exited+=new EventHandler(OnExit);

      p.StartInfo.FileName= "Notepad.exe";

     

      //you must enable this property or you won't get the event

      p.EnableRaisingEvents=true;

 

      p.Start();

 

      Console.WriteLine("Waiting...");

      Console.ReadLine();

}

 

private static void OnExit(object sender,EventArgs e)

{

      //here you get the event of a process close

      Console.WriteLine("The process was finished!");

}

 

You can also avoid using an event handler and simply make the code wait for the process(Synchronous invocation). Here are the two possibilities:

 

 

 

p.Start();

//wait indefinitely for the process to finish

p.WaitForExit();

//this line will be called only when the process finishes

Console.WriteLine("Waiting...");

 

 

Or you could wait for a maximum number of milliseconds(a sort of timeout):

 

p.Start();

//wait up to 5 seconds for the process to finish

p.WaitForExit(5000);

//this line will be called after 5 seconds

//or when the process finishes

Console.WriteLine("Waiting...");