Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait until multiple command line processes complete?

I have a need to execute many command line scripts. They are currently stored in a List. I want to run them all at the same time and proceed with the next step only after all of them have completed.

I have tried the approach that I show below, but found it lacking because the last command doesn't necessarily end last. In fact, I found that the last command can even be the first to complete. So, I believe that I need something like WaitForExit(), but which doesn't return until all executing processes have completed.

for (int i = 0; i < commands.Count; i++)
{
    string strCmdText = commands[i];
    var process = System.Diagnostics.Process.Start("CMD.exe", strCmdText);
    if (i == (commands.Count - 1))
    {
        process.WaitForExit();
    }
}
//next course of action once all the above is done
like image 389
fishmong3r Avatar asked May 19 '14 15:05

fishmong3r


1 Answers

Since each call to Process.Start starts a new process, you can track them all separately, like so:

var processes = new List<Process>();
for (int i = 0; i < commands.Count; i++)
{
    string strCmdText = commands[i];
    processes.Add(System.Diagnostics.Process.Start("CMD.exe", strCmdText));
}

foreach(var process in processes)
{
    process.WaitForExit();
    process.Close();
}

EDIT

Process.Close() added as in the comments

like image 113
Ben Aaronson Avatar answered Oct 21 '22 04:10

Ben Aaronson