Sunday, June 10, 2007

Implementing ThreadPool using C#

A thread pool is a collection of threads that can be used to perform a number of tasks in the background. Thread pool reduces the overhead of creating and destroying threads because when a thread in the pool completes its task, it is returned to a queue of waiting threads, where it can be reused. Thus enabling applications to avoid the cost of creating a new thread for each task.
There is one thread pool per process. The thread pool has a default size of 25 threads per available processor. The number of threads in the thread pool can be changed using the SetMaxThreads method. Each thread uses the default stack size and runs at the default priority.
Example-


using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;


class Program
{
///
/// The main entry point for the application.
///

[STAThread]
static void Main()
{
// Queue the task.
for (int i = 0; i < 3; i++)
{
switch (i)
{
case 0:
ThreadPool.QueueUserWorkItem(new WaitCallback(Task1));
break;
case 1:
ThreadPool.QueueUserWorkItem(new WaitCallback(Task2));
break;
case 2:
ThreadPool.QueueUserWorkItem(new WaitCallback(Task3), (object)"Task3");
break;
}
MessageBox.Show("Main thread does some work, then sleeps.");
// If you comment out the Sleep, the main thread exits before
// the thread pool task runs. The thread pool uses background
// threads, which do not keep the application running. (This
// is a simple example of a race condition.)
Thread.Sleep(3000);
}
}
// This thread procedure performs the task.
static void Task1(Object obj)
{
// No object was passed to QueueUserWorkItem, so
// obj is null.
MessageBox.Show("Hello from Taks1.");
}
static void Task2(Object obj)
{
// No object was passed to QueueUserWorkItem, so
// obj is null.
MessageBox.Show("Hello from Taks2.");
}
static void Task3(Object obj)
{
// An object was passed to QueueUserWorkItem that has a string value, so
// obj is cast to string type.
string str = (string)obj;
MessageBox.Show("Hello from " + str +".");
}
}

3 comments:

Anonymous said...

kind of useless and really ambiguous

Anonymous said...

Thanks for this, nice and simple and helps a lot! Ignore the fool's comment above.

Anonymous said...

where is wait handle, monitor, etc