QueueUserWorkItemCallback Delegate
Represents a method that accepts a single object argument and returns no value. This delegate is used with the ThreadPool.QueueUserWorkItem
method.
Syntax
public delegate void QueueUserWorkItemCallback(object state);
Remarks
The QueueUserWorkItemCallback
delegate is a fundamental part of .NET's asynchronous programming model, allowing tasks to be executed on threads managed by the system's thread pool.
When you call ThreadPool.QueueUserWorkItem
, you pass an instance of this delegate. The delegate's target method will be invoked by a thread from the thread pool when one becomes available. The state
object is passed to the method, allowing you to provide context or data to the work item.
Using the thread pool is generally more efficient than creating individual threads, as it reuses threads and manages their lifecycle. This can lead to better performance and resource utilization, especially in applications that perform many short-lived asynchronous operations.
The method represented by QueueUserWorkItemCallback
should not block for extended periods, as this can deplete the thread pool. If a long-running operation is necessary, consider using other asynchronous patterns like Task Parallel Library (TPL) or async/await
.
Example
using System;
using System.Threading;
public class Example
{
public static void Main()
{
Console.WriteLine("Main thread: Starting work.");
// Define the callback method that will run on a thread pool thread.
void MyCallback(object state)
{
// The 'state' object contains the data passed to QueueUserWorkItem.
string message = (string)state;
Console.WriteLine($"Worker thread: Processing '{message}'. Thread ID: {Thread.CurrentThread.ManagedThreadId}");
Thread.Sleep(1000); // Simulate work
Console.WriteLine($"Worker thread: Finished processing '{message}'.");
}
// Queue the work item to the thread pool.
// The 'MyCallback' method will be executed on a thread pool thread.
// The string "Hello from main!" is passed as the state object.
ThreadPool.QueueUserWorkItem(MyCallback, "Hello from main!");
Console.WriteLine("Main thread: Work item queued. Continuing execution.");
// Keep the main thread alive long enough for the worker thread to complete.
// In a real application, you might use events or other synchronization mechanisms.
Thread.Sleep(3000);
Console.WriteLine("Main thread: Exiting.");
}
}
Requirements
Namespace: System.Threading
Assembly: System.Runtime.dll (in .NET Core and .NET 5+), mscorlib.dll (in .NET Framework)