4

I'm executing 3 exes using Process.Start() in my C# application. I want to run all these exes sequentially. Right now, each Process.Start() executes on its own in a parallel manner.

eg:

Process.Start(exe1ForCopying_A_50_Mb_File);      
Process.Start(exe2ForCopying_A_10_Mb_File);  
Process.Start(exe3ForCopying_A_20_Mb_File);

I want my 2nd Process.Start() to start executing ONLY AFTER first Process.Start() has finished copying the 50 Mb file (which would be taking around 1 or 2 minutes).

Any suggestions?

Thanks.

madebydavid
  • 6,457
  • 2
  • 21
  • 29
Sandeep
  • 5,581
  • 10
  • 42
  • 62

3 Answers3

15

I think I got the answer myself..! :)

Process process = new Process(); 
ProcessStartInfo startInfo = new ProcessStartInfo(); 
startInfo.FileName = MyExe; 
startInfo.Arguments = ArgumentsForMyExe; 
process.StartInfo = startInfo; 
process.Start(); 
process.WaitForExit(); // This is the line which answers my question :) 

Thanks for the suggestion VAShhh..

Sandeep
  • 5,581
  • 10
  • 42
  • 62
0

You can:

VAShhh
  • 3,494
  • 2
  • 24
  • 37
  • 1
    I think I got the answer myself..! :) Process process = new Process(); ProcessStartInfo startInfo = new ProcessStartInfo(); startInfo.FileName = MyExe; startInfo.Arguments = ArgumentsForMyExe; process.StartInfo = startInfo; process.Start(); process.WaitForExit(); // This is the line which answers my question :) Thanks for the suggestion VAShhh.. – Sandeep Jun 06 '11 at 11:26
  • If i've understood this well the code you wrote make the program "block" or "wait" for the end of the parallel process. Are you sure that this will not cause the interface to freeze? Using events would not do so – VAShhh Jun 06 '11 at 11:30
0

You can either kick off a background thread or task and wait synchronously in a loop (using WaitForExit), or you can use an asynchronous approach.

Create the Process objects one by one and hook up an event handler to the Exited event that continues with the next Process. Create them with the Process constructor, hook the Exited event handler and then call Start; otherwise, using the static Process.Start, if the process fails between the time Process.Start returns and the event handler is attached, I think the event handler won't get called as it strictly has already exited.

Proof-of-concept: (doesn't handle Dispose, queue access isn't thread-safe, although it should suffice if it truly is serial, and so on)

Queue<Process> ProcessesToRun = new Queue<Process>(new []{ new Process("1"), new Process("2"), new Process("3") });

void ProcessExited(object sender, System.EventArgs e) {
    GrabNextProcessAndRun();
}

void GrabNextProcessAndRun() {
    if (ProcessesToRun.Count > 0) {
        Process process = ProcessesToRun.Dequeue();
        process.Exited += ProcessExited;
        process.Start();
    }
}

void TheEntryPoint() {
    GrabNextProcessAndRun();
}
Jesper
  • 79
  • 3