i'm working off a queue with filenames. Each file has to be processed by a external binary. This works fine, but it only processes one file at a time. Is it possible two spawn a number of processes parallel?
Queue<string> queue = new Queue<string>();
queue.Enqueue("1.mp3");
queue.Enqueue("2.mp3");
queue.Enqueue("3.mp3");
...
queue.Enqueue("10000.mp3");
while (queue.Count > 0)
{
string file = queue.Dequeue();
Process p = new Process();
p.StartInfo.FileName = @"binary.exe";
p.StartInfo.Arguments = file;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.Start();
p.WaitForExit();
}
Update: I like the solution from Alex LE (Spawn processes, but only 5 at a time), but is it possible to wait for the child processes to exit as suggested by Ben Voigt?
Edit 1: i need to check for p.ExitCode == 0 to make some database updates.
You can use semaphores for this and asynchronously call the long running process as much as you want:
hope this helps
This is one will block the Main thread partially base on Ben's answer, but this already run.
This works (this will be easier with C# 5.0 async await):
Exctracting some parts of your code and adding a semaphore:
You then use
Basically you have a producer consumer problem. So you should absolutely use the collections in the System.Collections.Concurrent namespace. Here is a simple example that you can simply apply to your problem - as a added bonus you can start filling the queue and its processing at the same time!
Here's what should have been possible, if the wait handle associated with the process was marked public instead of internal as it currently is (vote here to ask Microsoft to change that):
This would be the most efficient solution possible, because no synchronization objects are needed besides the Win32 processes themselves. There are no extra threads needed in the C# code and no asynchronous method invocations, therefore no locking or other synchronization is needed whatsoever.