jaks
jaks

Reputation: 4607

Creating a thread pooling in c#

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.

Upvotes: 1

Views: 1583

Answers (3)

David Storfer
David Storfer

Reputation: 360

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)

Upvotes: 2

BaBu
BaBu

Reputation: 1943

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.

Upvotes: 2

Paul Ruane
Paul Ruane

Reputation: 38620

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?

Upvotes: 3

Related Questions