开发者

Creating a thread pooling in c#

开发者 https://www.devze.com 2023-01-20 04:02 出处:网络
I have 300 threads which is executing one by one. I use join, so its one-by-one. I want to execute N threads at a time.

I have 300 threads which is executing one by one. I use join, so its one-by-one. I want to execute N threads at a time.

Can anyone direct me to a link on creating a thread pool in c# (with N threads). My situation is a开发者_开发知识库t a time N threads will execute, the rest of the threads will wait. When one thread finishes execution, one waiting thread will enter into execution.

Any code snippet is appreciated. Thanks a lot.


Join does not dictate that the threads are run sequentially — it merely makes the current thread wait for the specified thread to finish before continuing.

So if you start 300 threads and then join them all, the 300 threads will run in parallel and the joining thread will complete once the 300 threads are finished.

const int COUNT = 300;

// create and start the threads
var threads = new Thread[COUNT];
for (int index = 0; index < COUNT; index += 1)
{
    threads[index] = new Thread(...);
    threads[index].Start();
}

// now they're running, join them all
for (int index = 0; index < COUNT; index += 1)
{
    threads[index].Join();
}

// we're done

The important part is that you start them all before you start joining, otherwise you will wait for each thread to finish before starting the next, thus then they really would be sequential. I guess this is what you may be doing?


I think you are probably looking for ThreadPool.QueueUserWorkItem. Using the threadpool reduces the large overhead of thread creation and destruction. You can tune the threads (link in my comments) based on the hardware available, or allow the system to best manage the min/max simultaneous threads. If this is a web app, you can set this in your web.config to set your "N" thread number:

   <system.web>
        <processModel minWorkerThreads="50"/>
   </system.web>

If you are using .NET 4.0 you can also use the "Parallel.ForEach" which will automatically schedule each iteration of a loop onto a multiple threads in the thread pool. (link in my comments)


If most of your threads are waiting you should have a look at the System.Threading.ThreadPool class. It might just do exactly what you want. And it's efficient.

0

精彩评论

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