Thead Pooling

There are times you need to create different threads within your appliation. In this example you can create any amount of threads, queue them to start and they will close/open from the queue. This is how to get past the maxium of 25 threads at a time limit.

If you want a good example of the threads, open your Windows task manager, add Threads to your view and sort by threads while you run this test.

namespace ConsoleApplication1

class threading

static object worker = newobject();

statici nt runningworkers = 500;

public void Main()

{

for(inti = 0; i < runningworkers; i++)

{

ThreadPool.QueueUserWorkItem(RunThread, i);

}

lock(worker)

{

while(runningworkers > 0)

{

Monitor.Wait(worker);

}

Console.WriteLine("Complete...");

Console.ReadLine();

public static void RunThread(objectinstance)

{

Randomr = newRandom();

intsleep = r.Next(10000, 50000);

Thread.CurrentThread.Name = "Instance"+ instance;

Console.WriteLine("Started Instance: "+ instance + " Name: "+ Thread.CurrentThread.Name + " Managed ID: "+ Thread.CurrentThread.ManagedThreadId);

Thread.Sleep(sleep);

Console.WriteLine("Instance number "+ instance + " Ended after "+ sleep + " seconds"); 

lock(worker)

{

runningworkers--;

Monitor.Pulse(worker);

}

}

}

using System;
using System.Threading;
using System.Diagnostics;

Print | posted on Thursday, November 06, 2008 9:42 PM

This article is part of the GWB Archives. Original Author: Ken Lovely, MCSE, MCDBA

New on Geeks with Blogs