ThreadWaitCallback Delegate

Represents a callback method that is executed in a thread pool thread.

Syntax

public delegate void ThreadWaitCallback(object state);

Parameters

state (object)
An object containing application-specific information relevant to the callback method. This parameter can be null.

Remarks

The ThreadWaitCallback delegate is used by the ThreadPool.QueueUserWorkItem method. When you use ThreadPool.QueueUserWorkItem, you pass an instance of this delegate to the method. The thread pool then calls the delegate, passing the specified state object to it, when a thread becomes available.

The method represented by the delegate should be thread-safe, as it might be called by multiple threads. It should not throw exceptions that are not handled within the method itself, as unhandled exceptions in thread pool threads can terminate the application.

The ThreadWaitCallback delegate is a lightweight mechanism for queuing work items to the thread pool. For more complex scenarios, consider using the Task Parallel Library (TPL) or the ParameterizedThreadStart delegate with the Thread class.

Example


using System;
using System.Threading;

public class Example
{
    public static void Main()
    {
        // The object to pass to the callback method.
        object stateInfo = "Some data for the callback.";

        // Queue the work item.
        bool queued = ThreadPool.QueueUserWorkItem(
            new WaitCallback(MyThreadWaitCallback),
            stateInfo);

        if (queued)
        {
            Console.WriteLine("Work item queued successfully.");
        }
        else
        {
            Console.WriteLine("Failed to queue work item.");
        }

        // Keep the main thread alive to allow the callback to execute.
        Console.WriteLine("Main thread waiting. Press Enter to exit.");
        Console.ReadLine();
    }

    // This method is executed by a thread pool thread.
    public static void MyThreadWaitCallback(object state)
    {
        Console.WriteLine($"Callback executed in thread: {Thread.CurrentThread.ManagedThreadId}");
        if (state != null)
        {
            Console.WriteLine($"Received state: {state}");
        }
        // Simulate some work.
        Thread.Sleep(1000);
        Console.WriteLine("Callback finished.");
    }
}

See Also