Tuesday, April 5, 2011

Wait till a process ends

I've an application which does

Process.Start()

to start another application 'ABC'. I want to wait till that application ends (process dies) and continue my execution. How can i do it?

There may be multiple instances of the application 'ABC' running at the same time.

Any insights?

From stackoverflow
  • Use Process.WaitForExit? Or subscribe to the Process.Exited event if you don't want to block? If that doesn't do what you want, please give us more information about your requirements.

    NLV : +1 for the event.
  • I think you just want this:

    var process = Process.Start(...);
    process.WaitForExit();
    

    See the MSDN page for the method. It also has an overload where you can specify the timeout, so you're not potentially waiting forever.

    this. __curious_geek : +1. simple and elegant.
  • Process.WaitForExit should be just what you're looking for I think.

  • You could use wait for exit or you can catch the HasExited property and update your UI to keep the user "informed" (expectation management):

            System.Diagnostics.Process process = System.Diagnostics.Process.Start("cmd.exe");
            while (!process.HasExited)
            {
                //update UI
            }
            //done
    
  • I do the following in my Application:

    Process process = new Process();
    process.StartInfo.FileName = executable;
    process.StartInfo.Arguments = arguments;
    process.StartInfo.ErrorDialog = true;
    process.StartInfo.WindowStyle = ProcessWindowStyle.Minimized;
    process.Start();
    process.WaitForExit(1000 * 60 * 5);    // wait up to 5 minutes.
    

    There are few extra features in there which you might find useful...

0 comments:

Post a Comment