ThreadPool Class

Namespace: System.Threading

Provides a set of methods that allow you to use the managed thread pool features of the .NET Framework.

Note: This class is fundamental for efficient multithreaded operations in .NET.

Syntax

[System.Runtime.InteropServices.ComVisibleAttribute(true)]
public static class ThreadPool

Remarks

The thread pool is a collection of application domain-wide threads that can be used to execute tasks. When you create a thread yourself, you have to explicitly start it. When you queue a task to the thread pool, the thread pool itself selects an appropriate thread to execute the task. This can improve application performance because the threads in the pool are initialized and ready to use.

The .NET Framework manages the threads in the thread pool. By default, the number of threads in the pool is determined by the .NET Framework, but you can configure the maximum number of threads.

The ThreadPool class provides methods for queueing work items, managing thread pool size, and retrieving information about the thread pool.

Methods

QueueUserWorkItem

Queues a method for execution. The method executes asynchronously on a thread pool thread.

public static bool QueueUserWorkItem(WaitCallback callBack);
public static bool QueueUserWorkItem(WaitCallback callBack, object state);
public static bool QueueUserWorkItem(Action callBack);
public static bool QueueUserWorkItem(Action callBack, object state);
// ... and other overloads

            

Parameters:

  • callBack: A WaitCallback delegate that represents the method to be executed.
  • state: An object containing information to be used by the method. This parameter can be null.

Returns: true if the method was successfully queued; otherwise, false.

Tip: Use QueueUserWorkItem for short-lived tasks that don't require specific thread control.

SetMaxThreads

Sets the maximum number of worker threads that can be simultaneously active in the thread pool.

public static void SetMaxThreads(int workerThreads, int completionPortThreads);

Parameters:

  • workerThreads: The maximum number of worker threads.
  • completionPortThreads: The maximum number of I/O completion threads.

GetMaxThreads

Retrieves the maximum number of worker threads and I/O completion threads that can be simultaneously active in the thread pool.

public static void GetMaxThreads(out int workerThreads, out int completionPortThreads);

Returns: The maximum number of worker threads and I/O completion threads.

See Also

Important: Modifying thread pool settings can have significant performance implications. Use caution when calling SetMaxThreads.