Reputation: 75
I have a need to process 100 pieces of information through an external program. These processes can be intensive, so I need to limit it to processing 8 at a time. Essentially, I'd like to launch 8 processes, and as each one completes, launch the next one.
I have attempted to use TPL in System.Threading.Tasks.Dataflow with the below code, but all 100 launch, not just 8 at a time.
// This file has the command line parameters to launch the external process
List<string> lines = File.ReadAllLines(file).ToList();
var block = new ActionBlock<string>(async job => await RunJob(job), new ExecutionDataflowBlockOptions { MaxDegreeOfParallelism = 1 });
foreach (string line in lines)
{
block.SendAsync(line);
}
static async Task RunJob(string parms)
{
//Console.WriteLine("PARMS: {0}", parms);
Process proc = new Process();
ProcessStartInfo start = new ProcessStartInfo();
start.WindowStyle = ProcessWindowStyle.Normal;
start.FileName = @"C:\program.exe";
string parameters = String.Format(parms.ToString());
start.Arguments = parameters;
start.UseShellExecute = true;
proc.StartInfo = start;
proc.Start();
}
What have I missed? Thanks for the help.
Upvotes: 3
Views: 200
Reputation: 9501
Process starts immediately, but you don't wait until process ends. Use proc.WaitForExit();
static async Task RunJob(string parms)
{
//Console.WriteLine("PARMS: {0}", parms);
Process proc = new Process();
ProcessStartInfo start = new ProcessStartInfo();
start.WindowStyle = ProcessWindowStyle.Normal;
start.FileName = @"C:\program.exe";
string parameters = String.Format(parms.ToString());
start.Arguments = parameters;
start.UseShellExecute = true;
proc.StartInfo = start;
proc.Start();
proc.WaitForExit();
}
Upvotes: 2