Home > Mobile >  How to call multiple batch scripts in C# console and wait for them to finish
How to call multiple batch scripts in C# console and wait for them to finish

Time:12-13

I need to run four batch scripts, (for testing purposes contsining just I'm timeout /t 10 /nobreak > NUL.

I need to execute the files at the same time, and wait for all of them to finish, before repeating with a different set of batch scripts.

This is my code by now:

Process process = new Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.CreateNoWindow = true;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.Start();

process.StandardInput.WriteLine(command);
process.StandardInput.Flush();
process.StandardInput.Close();
System.Diagnostics.Process.Start(command).WaitForExit();
//process.WaitForExit();

Console.WriteLine(process.StandardOutput.ReadToEnd());

CodePudding user response:

You haven't show us the contents of the Batch file you execute via your process object. Such a Batch file could be the one in charge of execute the 4 desired Batch files and wait for all of them to finish. That is:

@echo off
(
start "" Batch1.bat
start "" Batch2.bat
start "" Batch3.bat
start "" Batch4.bat
) | pause
echo The 4 Batch files have ended!

In this way your C# program would be simpler...

You can read the explanation of this method at this answer

CodePudding user response:

If you have a function that executes a command (runOneCommand), you can use the following method:

List<Task> tl = new List<Task>();
tl.Add(Task.Factory.StartNew(() => runOneCommand("command1..."));
tl.Add(Task.Factory.StartNew(() => runOneCommand("command2..."));
tl.Add(Task.Factory.StartNew(() => runOneCommand("command3..."));
tl.Add(Task.Factory.StartNew(() => runOneCommand("command4..."));

Task.WaitAll(tl.ToArray());

The second way is to use Thread.Join, which you can read about in this link: Thread.Join

  • Related