开发者

Best way of controlling the number of simultaneous threads in c#

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开发者_Python百科 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.

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


Semaphores are a common technique to do this.


Why not use something built-in like:

  1. The threadpool (ThreadPool.QueueUserWorkItem)
  2. The task-parallels library
  3. Parallel-LINQ
  4. Parallel.ForEach

Example:

Parallel.ForEach(objList,doSomething);


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜