简体   繁体   English

在C#中创建线程池

[英]Creating a thread pooling in c#

I have 300 threads which is executing one by one. 我有300个线程正在一个接一个地执行。 I use join, so its one-by-one. 我使用join,所以它是一对一的。 I want to execute N threads at a time. 我想一次执行N个线程。

Can anyone direct me to a link on creating a thread pool in c# (with N threads). 谁能将我定向到在c#中创建线程池(带有N个线程)的链接。 My situation is at a time N threads will execute, the rest of the threads will wait. 我的情况是,一次将执行N个线程,其余线程将等待。 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. Join并不指示线程按顺序运行-只是使当前线程在继续执行之前等待指定线程完成。

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. 因此,如果先启动300个线程然后将它们全部加入,则这300个线程将并行运行,并且当300个线程完成后,连接线程将完成。

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? 我想这可能是您在做什么?

If most of your threads are waiting you should have a look at the System.Threading.ThreadPool class. 如果大多数线程都在等待,则应查看System.Threading.ThreadPool类。 It might just do exactly what you want. 它可能恰好可以满足您的要求。 And it's efficient. 而且效率很高。

I think you are probably looking for ThreadPool.QueueUserWorkItem . 我认为您可能正在寻找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: 如果这是一个Web应用程序,则可以在web.config中进行设置,以设置“ N”线程号:

   <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. 如果使用的是.NET 4.0,则还可以使用“ Parallel.ForEach”,它将自动将循环的每次迭代安排到线程池中的多个线程上。 (link in my comments) (在我的评论中链接)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM