Linit the number of external process running at any one time

J

Jeff

I need to run many processes from my application. and I am using the
following enclosed in a for next loop:

System.Diagnostics.Process runObj = new System.Diagnostics.Process();
runObj.StartInfo.FileName = exepath;
runObj.Start();

What I want to do is limit the number of of process which are run at any
one time. So if I have 20 processes to run I can limit it to 10
consecutive processes. When a process finishes the next in the list
starts untill all process finish.

How could I achieve this using this code or is there a better way of
doing this.

Regards
Jeff
 
M

Marc Gravell

Sounds like a semaphore might be the simplest answer:

Semaphore count = new Semaphore(5, 5);
for (int i = 0; i < 20; i++)
{
count.WaitOne();
ThreadPool.QueueUserWorkItem(state =>
{
Process.Start("notepad.exe").WaitForExit();
count.Release();
});
}

I tried to use the Exited event (rather than ThreadPool), but it didn't
seem to raise...

Marc
 
M

Marc Gravell

For the OP's benefit - the same without the ThreadStart would be:

Semaphore count = new Semaphore(5, 5);
for (int i = 0; i < 20; i++)
{
count.WaitOne();

Process proc = new Process();
proc.StartInfo = new ProcessStartInfo("notepad.exe");
proc.EnableRaisingEvents = true;
proc.Exited += delegate
{
count.Release();
proc.Dispose();
};
proc.Start();
}

Obviously you might be picking successive commands out of an array /
list, rather than using "notepad.exe" each time ;-p

Marc
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top