我需要通过外部程序处理100条信息。这些过程可能非常耗时,因此我需要将其限制为一次只能处理8个。本质上,我想启动8个进程,并在每个进程完成后启动下一个进程。
我试图通过以下代码在System.Threading.Tasks.Dataflow中使用TPL,但要全部100次启动,而不是一次只启动8次。
// 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();
}
我错过了什么?感谢您的帮助。
答案 0 :(得分:2)
过程立即开始,但是您不必等到过程结束。使用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();
}