建立在C#中的线程池 [英] Creating a thread pooling in c#

查看:359
本文介绍了建立在C#中的线程池的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个正在执行一个接一个300线程。我用加入,所以它的一个接一个。我想,在一次执行N个线程。

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.

任何人都可以直接我一个链接,创建在C#中的线程池(有N个线程)。我的情况是在一个时间N个线程会执行,线程的其余部分将等待。当一个线程执行完毕,一个等待的线程将进入执行。

Can anyone direct me to a link on creating a thread pool in c# (with N threads). My situation is at 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.

任何code段是AP preciated。非常感谢。

Any code snippet is appreciated. Thanks a lot.

推荐答案

我想你可能寻找的 ThreadPool.QueueUserWorkItem 。使用线程池减少了创建和销毁线程的大的开销。您可以调整根据可用的硬件线程(在我的评论链接),或者让系统最佳管理最小/最大并发线程。如果这是一个Web应用程序,你可以把这个在你的web.config设置你的N线​​程编号:

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>

如果您使用的是.NET 4.0中,您还可以使用Parallel.ForEach,它会自动安排循环的每个迭代上的线程池中的多个线程。 (在我的评论链接)

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)

这篇关于建立在C#中的线程池的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆