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
Use a Task array and wait for all of them to complete.
Or, more LINQ-ishly like this:
Since each call to
Process.Start
starts a new process, you can track them all separately, like so:EDIT
Process.Close()
added as in the commentsAt least on Windows, you could use
WaitHandle.WaitAll()
.This approach offers the possibility to also use other
WaitAll
overloads, and wait with timeouts, for example.