ThreadPool.QueueUserWorkItem Method

Definition

Queues a method for execution. The method executes when a thread pool thread becomes available.

Overloads

QueueUserWorkItem(WaitCallback)

Queues a method for execution. The method executes when a thread pool thread becomes available.

QueueUserWorkItem(WaitCallback, Object)

Queues a method for execution, and specifies an object containing data to be used by the method. The method executes when a thread pool thread becomes available.

QueueUserWorkItem<TState>(Action<TState>, TState, Boolean)

Queues a method specified by an Action<T> delegate for execution, and provides data to be used by the method. The method executes when a thread pool thread becomes available.

QueueUserWorkItem(WaitCallback)

Source:
ThreadPoolWorkQueue.cs
Source:
ThreadPoolWorkQueue.cs
Source:
ThreadPoolWorkQueue.cs

Queues a method for execution. The method executes when a thread pool thread becomes available.

C#
public static bool QueueUserWorkItem(System.Threading.WaitCallback callBack);

Parameters

callBack
WaitCallback

A WaitCallback that represents the method to be executed.

Returns

true if the method is successfully queued; NotSupportedException is thrown if the work item could not be queued.

Exceptions

callBack is null.

The common language runtime (CLR) is hosted, and the host does not support this action.

Examples

The following example uses the QueueUserWorkItem(WaitCallback) method overload to queue a task, which is represented by the ThreadProc method, to execute when a thread becomes available. No task information is supplied with this overload. Therefore, the information that is available to the ThreadProc method is limited to the object the method belongs to.

C#
using System;
using System.Threading;

public class Example 
{
    public static void Main() 
    {
        // Queue the task.
        ThreadPool.QueueUserWorkItem(ThreadProc);
        Console.WriteLine("Main thread does some work, then sleeps.");
        Thread.Sleep(1000);

        Console.WriteLine("Main thread exits.");
    }

    // This thread procedure performs the task.
    static void ThreadProc(Object stateInfo) 
    {
        // No state object was passed to QueueUserWorkItem, so stateInfo is null.
        Console.WriteLine("Hello from the thread pool.");
    }
}
// The example displays output like the following:
//       Main thread does some work, then sleeps.
//       Hello from the thread pool.
//       Main thread exits.

Remarks

You can place data required by the queued method in the instance fields of the class in which the method is defined, or you can use the QueueUserWorkItem(WaitCallback, Object) overload that accepts an object containing the necessary data.

Note

Visual Basic users can omit the WaitCallback constructor, and simply use the AddressOf operator when passing the callback method to QueueUserWorkItem. Visual Basic automatically calls the correct delegate constructor.

The Thread.CurrentPrincipal property value is propagated to worker threads queued using the QueueUserWorkItem method.

See also

Applies to

.NET 10 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

QueueUserWorkItem(WaitCallback, Object)

Source:
ThreadPoolWorkQueue.cs
Source:
ThreadPoolWorkQueue.cs
Source:
ThreadPoolWorkQueue.cs

Queues a method for execution, and specifies an object containing data to be used by the method. The method executes when a thread pool thread becomes available.

C#
public static bool QueueUserWorkItem(System.Threading.WaitCallback callBack, object? state);
C#
public static bool QueueUserWorkItem(System.Threading.WaitCallback callBack, object state);

Parameters

callBack
WaitCallback

A WaitCallback representing the method to execute.

state
Object

An object containing data to be used by the method.

Returns

true if the method is successfully queued; NotSupportedException is thrown if the work item could not be queued.

Exceptions

The common language runtime (CLR) is hosted, and the host does not support this action.

callBack is null.

Examples

The following example uses the .NET thread pool to calculate the Fibonacci result for five numbers between 20 and 40. Each Fibonacci result is represented by the Fibonacci class, which provides a method named ThreadPoolCallback that performs the calculation. An object that represents each Fibonacci value is created, and the ThreadPoolCallback method is passed to QueueUserWorkItem, which assigns an available thread in the pool to execute the method.

Because each Fibonacci object is given a semi-random value to compute, and because each thread will be competing for processor time, you cannot know in advance how long it will take for all five results to be calculated. That is why each Fibonacci object is passed an instance of the ManualResetEvent class during construction. Each object signals the provided event object when its calculation is complete, which allows the primary thread to block execution with WaitAll until all five Fibonacci objects have calculated a result. The Main method then displays each Fibonacci result.

C#
using System;
using System.Threading;

public class Fibonacci
{
    private ManualResetEvent _doneEvent;

    public Fibonacci(int n, ManualResetEvent doneEvent)
    {
        N = n;
        _doneEvent = doneEvent;
    }

    public int N { get; }

    public int FibOfN { get; private set; }

    public void ThreadPoolCallback(Object threadContext)
    {
        int threadIndex = (int)threadContext;
        Console.WriteLine($"Thread {threadIndex} started...");
        FibOfN = Calculate(N);
        Console.WriteLine($"Thread {threadIndex} result calculated...");
        _doneEvent.Set();
    }

    public int Calculate(int n)
    {
        if (n <= 1)
        {
            return n;
        }
        return Calculate(n - 1) + Calculate(n - 2);
    }
}

public class ThreadPoolExample
{
    static void Main()
    {
        const int FibonacciCalculations = 5;

        var doneEvents = new ManualResetEvent[FibonacciCalculations];
        var fibArray = new Fibonacci[FibonacciCalculations];
        var rand = new Random();

        Console.WriteLine($"Launching {FibonacciCalculations} tasks...");
        for (int i = 0; i < FibonacciCalculations; i++)
        {
            doneEvents[i] = new ManualResetEvent(false);
            var f = new Fibonacci(rand.Next(20, 40), doneEvents[i]);
            fibArray[i] = f;
            ThreadPool.QueueUserWorkItem(f.ThreadPoolCallback, i);
        }

        WaitHandle.WaitAll(doneEvents);
        Console.WriteLine("All calculations are complete.");

        for (int i = 0; i < FibonacciCalculations; i++)
        {
            Fibonacci f = fibArray[i];
            Console.WriteLine($"Fibonacci({f.N}) = {f.FibOfN}");
        }
    }
}
// The output is similar to:
// Launching 5 tasks...
// Thread 3 started...
// Thread 4 started...
// Thread 2 started...
// Thread 1 started...
// Thread 0 started...
// Thread 2 result calculated...
// Thread 3 result calculated...
// Thread 4 result calculated...
// Thread 1 result calculated...
// Thread 0 result calculated...
// All calculations are complete.
// Fibonacci(35) = 9227465
// Fibonacci(27) = 196418
// Fibonacci(25) = 75025
// Fibonacci(25) = 75025
// Fibonacci(27) = 196418

Remarks

If the callback method requires complex data, you can define a class to contain the data.

Note

Visual Basic users can omit the WaitCallback constructor, and simply use the AddressOf operator when passing the callback method to QueueUserWorkItem. Visual Basic automatically calls the correct delegate constructor.

See also

Applies to

.NET 10 and other versions
Product Versions
.NET Core 1.0, Core 1.1, Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

QueueUserWorkItem<TState>(Action<TState>, TState, Boolean)

Source:
ThreadPoolWorkQueue.cs
Source:
ThreadPoolWorkQueue.cs
Source:
ThreadPoolWorkQueue.cs

Queues a method specified by an Action<T> delegate for execution, and provides data to be used by the method. The method executes when a thread pool thread becomes available.

C#
public static bool QueueUserWorkItem<TState>(Action<TState> callBack, TState state, bool preferLocal);

Type Parameters

TState

The type of elements of state.

Parameters

callBack
Action<TState>

An Action<T> representing the method to execute.

state
TState

An object containing data to be used by the method.

preferLocal
Boolean

true to prefer queueing the work item in a queue close to the current thread; false to prefer queueing the work item to the thread pool's shared queue.

Returns

true if the method is successfully queued; NotSupportedException is thrown if the work item could not be queued.

Applies to

.NET 10 and other versions
Product Versions
.NET Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9, 10
.NET Standard 2.1