ThreadPool Class
Namespace: System.Threading
Provides a pool of threads that can be used to execute operations. This class cannot be inherited.
Summary
The ThreadPool class in .NET Core allows you to manage a collection of worker threads that are available to execute tasks. Instead of creating a new thread for each operation, you can queue work items to the thread pool. The thread pool efficiently manages the threads, reusing them as needed to minimize the overhead of thread creation and destruction. This is crucial for scalability and performance in applications that perform many asynchronous operations.
Methods
QueueUserWorkItem
Queues a method for execution by the thread pool resource. This is the most common way to submit work to the thread pool.
public static bool QueueUserWorkItem(WaitCallback callback, object state)callback: A WaitCallback delegate that represents the method to be executed.state: An object containing information to be used by the delegate. This parameter can benull.
true if the method was successfully queued; otherwise, false.
callback: A WaitCallback delegate that represents the method to be executed.
true if the method was successfully queued; otherwise, false.
RegisterWaitForSingleObject
Registers a method to be called after a specified interval, or when a WaitHandle is signaled.
public static RegisteredWaitHandle RegisterWaitForSingleObject(WaitHandle waitObject, WaitCallback callBack, object state, TimeSpan timeOut, bool executeOnlyOnce)waitObject: The WaitHandle to wait for.callBack: A WaitCallback delegate that represents the method to be executed.state: An object containing information to be used by the delegate.timeOut: The time interval to wait.executeOnlyOnce:trueto execute the callback only once;falseto execute it every time thewaitObjectis signaled.
A RegisteredWaitHandle that can be used to unregister the callback.
SetMaxThreads
Sets the maximum number of worker threads that can be created by the thread pool.
public static void SetMaxThreads(int workerThreads, int completionPortThreads)workerThreads: The maximum number of worker threads.completionPortThreads: The maximum number of I/O completion threads.
SetMinThreads
Sets the minimum number of worker threads that can be created by the thread pool.
public static void SetMinThreads(int workerThreads, int completionPortThreads)workerThreads: The minimum number of worker threads.completionPortThreads: The minimum number of I/O completion threads.
GetMaxThreads
Gets the maximum number of worker threads that can be created by the thread pool.
public static void GetMaxThreads(out int workerThreads, out int completionPortThreads)workerThreads: [Output] Receives the maximum number of worker threads.completionPortThreads: [Output] Receives the maximum number of I/O completion threads.
GetMinThreads
Gets the minimum number of worker threads that can be created by the thread pool.
public static void GetMinThreads(out int workerThreads, out int completionPortThreads)workerThreads: [Output] Receives the minimum number of worker threads.completionPortThreads: [Output] Receives the minimum number of I/O completion threads.
Example Usage
The following example demonstrates how to queue a work item to the thread pool:
using System;
using System.Threading;
public class Example
{
public static void Main(string[] args)
{
Console.WriteLine($"Main thread: {Thread.CurrentThread.ManagedThreadId}");
// Queue a work item to the thread pool
bool queued = ThreadPool.QueueUserWorkItem(ProcessData, "Sample Data");
if (queued)
{
Console.WriteLine("Work item queued successfully.");
}
else
{
Console.WriteLine("Failed to queue work item.");
}
// Keep the main thread alive for a bit to allow the work item to execute
Thread.Sleep(2000);
Console.WriteLine("Main thread exiting.");
}
// This method will be executed by a thread pool thread
private static void ProcessData(object state)
{
string data = state as string;
Console.WriteLine($"Processing data: '{data}' on thread: {Thread.CurrentThread.ManagedThreadId}");
Thread.Sleep(500); // Simulate work
Console.WriteLine($"Finished processing on thread: {Thread.CurrentThread.ManagedThreadId}");
}
}
Remarks
The .NET thread pool is managed by the runtime and automatically adjusts the number of threads based on the workload. For most scenarios, you don't need to explicitly configure the thread pool's size. However, in performance-critical applications, you might need to tune the minimum and maximum number of threads using SetMinThreads and SetMaxThreads.
When using QueueUserWorkItem, it's important to ensure that the work item does not block indefinitely, as this can lead to thread pool starvation. Consider using Task.Run with Task-based asynchronous patterns for more modern and robust asynchronous programming.