C# Reference ยท Async and Concurrency
The ThreadPool class
Reference for System.Threading.ThreadPool in C#: queue work items, read and set thread limits, understand starvation and why Task.Run is usually better.
The thread pool is a shared set of worker threads that .NET manages for you. Instead of creating a thread per job, you queue a small piece of work and an idle pool thread picks it up. The runtime adds and removes threads based on load.
Task.Run, async continuations, Parallel, timers and Task.Delay all use the pool. The ThreadPool class itself is the low-level API: queue a delegate, inspect limits. Most programs only call it indirectly.
ThreadPool.QueueUserWorkItem(_ => Console.WriteLine("on the pool"));
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public static class ThreadPool { public static bool QueueUserWorkItem(WaitCallback callBack); public static bool QueueUserWorkItem(WaitCallback callBack, object? state); public static bool QueueUserWorkItem<TState>( Action<TState> callBack, TState state, bool preferLocal); public static bool UnsafeQueueUserWorkItem(WaitCallback callBack, object? state); public static bool SetMinThreads(int workerThreads, int completionPortThreads); public static bool SetMaxThreads(int workerThreads, int completionPortThreads); public static void GetMinThreads(out int workerThreads, out int completionPortThreads); public static void GetMaxThreads(out int workerThreads, out int completionPortThreads); public static void GetAvailableThreads(out int workerThreads, out int completionPortThreads); public static int ThreadCount { get; } public static long PendingWorkItemCount { get; } public static long CompletedWorkItemCount { get; } public static RegisteredWaitHandle RegisterWaitForSingleObject( WaitHandle waitObject, WaitOrTimerCallback callBack, object? state, int millisecondsTimeOutInterval, bool executeOnlyOnce); }
| Name | Description |
|---|---|
callBack |
The delegate to run on a pool thread. |
state |
Data passed to the callback. The generic overload avoids boxing. |
preferLocal |
true queues to the current worker's local queue, which is faster but less fair. |
workerThreads |
Threads for ordinary work items and task continuations. |
completionPortThreads |
Threads for I/O completions (meaningful on Windows). |
Returns: QueueUserWorkItem returns true when the item was queued. Set*Threads return false if the values are invalid.
Errors: an unhandled exception in a work item terminates the process, exactly like an unhandled exception in a plain thread.
Usage notes
- Prefer
Task.Run. It queues to the same pool and gives you aTaskfor results, exceptions and cancellation. UseQueueUserWorkItemonly for fire-and-forget work with no result. - Pool threads are background threads. If
Mainreturns, queued work that has not finished is abandoned. Wait with a latch, a task or aCountdownEvent. - Starvation. If work items block (waiting on locks,
.Result,Thread.Sleep), the pool has no free thread for the work they wait on. It injects new threads slowly (about one or two per second after the minimum). Useawaitinstead of blocking. - The minimum is a burst allowance. The pool starts new threads immediately only up to the minimum, which defaults to the processor count. Raising it with
SetMinThreadshides starvation instead of fixing it. - Do not run long jobs on the pool. A work item that runs for minutes occupies a worker. Use a dedicated Thread or
TaskCreationOptions.LongRunning. - Do not change thread properties. Never rename, set priority or make pool threads foreground; they are returned to the pool.
- State flows with the execution context.
AsyncLocal<T>values are captured byQueueUserWorkItem;UnsafeQueueUserWorkItemskips that capture.
Related
- Thread, Task.Run(), Timer, Parallel.For and ForEach
- Lessons: Threads, Tasks