Overview
The ThreadPool class provides a pool of worker threads that can be used to execute short-lived tasks without the overhead of creating dedicated threads. It is part of the System.Threading namespace.
Using the Thread Pool
Typical scenarios for the thread pool include I/O completion, background processing, and parallelization of CPU‑bound work.
Queueing a Work Item
using System;
using System.Threading;
class Program
{
static void Main()
{
// Queue a simple work item.
ThreadPool.QueueUserWorkItem(DoWork, "Hello from the thread pool!");
Console.WriteLine("Main thread continues...");
Console.ReadKey();
}
static void DoWork(object state)
{
Console.WriteLine(state);
// Simulate work.
Thread.Sleep(1000);
Console.WriteLine("Work completed.");
}
}
Advanced Options
- SetMinThreads / SetMaxThreads: Adjust the number of threads the pool can allocate.
- RegisterWaitForSingleObject: Use the thread pool for waiting on handles.
- LongRunning Tasks: For tasks that run for a long time, consider
TaskCreationOptions.LongRunninginstead of the thread pool.
Remarks
The thread pool reuses threads, which reduces the cost of thread creation and destruction. However, the pool may delay execution of queued work items if all threads are busy. Always design work items to be short and non‑blocking.