Reputation: 1522
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?
Upvotes: 2
Views: 738
Reputation: 2714
If you are using .net prior to 4.0, then you should write a multi-threaded producer consumer queue. In the constructor you can specify your worker thread limit. The benefit of doing it this way, is that you can separate your worker thread creation and thread synchronization, from your actual functional code. There are many examples on the web and StackOverflow.
If you are using .net 4.0; obviously there are the System.Collections.Concurrent types for you to look at and Parallel types previously mentioned.
Upvotes: 1
Reputation: 18832
You can do this with the Task parallel library included with .net 4.
ParallelOptions options = new ParallelOptions();
options.MaxDegreeOfParallelism = 25;
Parallel.ForEach(objList, options, item => doSomething(item));
Parallel.ForEach
has 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
Upvotes: 1
Reputation: 17556
You can make use of Semaphores if using .net 2.0 or later.
Semaphore will let you to define a max limit of threds and when you can release on semaphore object to enter waiting threads if the number of threads are greater than specified limit in semaphore object.
Upvotes: 1
Reputation: 108880
Why not use something built-in like:
Example:
Parallel.ForEach(objList,doSomething);
Upvotes: 1