I have a simple multi-threaded program, with the following structure.
public void someFunction()
{
List<object> objList = new List<object>();
//objList populated here
foreach(object o in objList)
{
Thread aThread = new Thread (new ParameterizedThreadStart(doSomething));
aThread.Start(o);
}
}
static void doSomething(object o)
{
//Do something with o.
}
This works well, but I’m having issues limiting the number of simultaneous theads running. Say I want to define int maxThreads = 25 for example. The best way I could think of doing it would be something like:
SomeThreadsafeCounter c = new SomeThreadsafeCounter();
foreach(object o in objList)
{
while (c < 26){ wait; }
c++;
Thread aThread = new Thread (new ParameterizedThreadStart(doSomething));
aThread.Start(o);
c--;
}
I’m certain this isn’t the correct way to go about it, is there a better way?
You can do this with the Task parallel library included with .net 4.
Parallel.ForEachhas a number of overloads and I am not sure that I have the correct one here.More info here: http://msdn.microsoft.com/en-us/library/dd537608.aspx