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 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.
Any code snippet is appreciated. Thanks a lot.
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:
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)