Question

I am executing another .exe file inside my c# code but I need to be sure that .exe file has done its work so my code can run the rest. Here is my code.

Process p = new Process();
p.StartInfo.FileName = path;
p.Start();
////// stop untill previous file finish its job
p.StartInfo.FileName = newpath;
p.Start();
Was it helpful?

Solution

If you don't care if your main thread is blocked, just call Process.WaitForExit();

Process p = new Process();
p.StartInfo.FileName = path;
p.Start();
p.WaitForExit(timeout);
var p2 = new Process();
p2.StartInfo.FileName = newpath;
p2.Start();

OTHER TIPS

According to MSDN:

You can use p.HasExited.

You can also set an Exited event handler as described here.

So in your case, you've two ways to solve your problem. Or you actively wait for the process to exit by looping and sleeping until the condition p.HasExit is true, or you can set an Exited event handler (recommended method). Here's an example for the EventHandler method:

private void your_ExitedHandler(object sender, System.EventArgs e) {
    /* ... */
    Process p = new Process();
    p.StartInfo.FileName = "your\\new\\path\\bin.exe";
    p.Start();
    /* ... */
}

public void yourFunction() {
    /* ... */
    Process p = new Process();
    p.StartInfo.FileName = path;
    p.EnableRaisingEvents = true;
    p.Exited += new EventHandler(your_ExitedHandler);
    p.Start();
    /* ... */
}

And here's an example with sleep (this will cause the UI, if applicable, to block if executed in the main thread):

Process p = new Process();
p.StartInfo.FileName = path;
p.Start();

/* Wait for process to exit. WARNING: This will block the UI if executed in the main thread... */
while (!p.HasExited) {
    System.Threading.Thread.Sleep(200); // Wait 200ms before testing p.HasExited again.
}
/* Process exited */

p.StartInfo.FileName = newpath;
p.Start();

If your application is GUI based, you can take a look into the BackgroundWorker class.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top