ThreadPool.QueueUserWorkItem Method

Definition

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(WaitCallback)

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

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.

using namespace System;
using namespace System::Threading;

ref class Example
{
public:

   // This thread procedure performs the task.
   static void ThreadProc(Object^ stateInfo)
   {
      
      // No state object was passed to QueueUserWorkItem, so stateInfo is 0.
      Console::WriteLine( "Hello from the thread pool." );
   }
};

int main()
{
   // Queue the task.
   ThreadPool::QueueUserWorkItem(gcnew WaitCallback(Example::ThreadProc));

   Console::WriteLine("Main thread does some work, then sleeps.");
   
   Thread::Sleep(1000);
   Console::WriteLine("Main thread exits.");
   return 0;
}
// The example displays output like the following:
//       Main thread does some work, then sleeps.
//       Hello from the thread pool.
//       Main thread exits.
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.
Imports System.Threading

Public Module Example
    Public Sub Main()
        ' Queue the work for execution.
        ThreadPool.QueueUserWorkItem(AddressOf ThreadProc)
        
        Console.WriteLine("Main thread does some work, then sleeps.")

        Thread.Sleep(1000)

        Console.WriteLine("Main thread exits.")
    End Sub

    ' This thread procedure performs the task.
    Sub ThreadProc(stateInfo As Object)
        ' No state object was passed to QueueUserWorkItem, so stateInfo is null.
        Console.WriteLine("Hello from the thread pool.")
    End Sub
End Module
' 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.

Version Information

In the .NET Framework version 2.0, the Thread.CurrentPrincipal property value is propagated to worker threads queued using the QueueUserWorkItem method. In earlier versions, the principal information is not propagated.

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.

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 shows how to create an object that contains task information. It also demonstrates how to pass that object to a task that is queued for execution by the thread pool.

// This example shows how to create an Object* containing task
// information, and pass that Object* to a task queued for
// execution by the thread pool.
using namespace System;
using namespace System::Threading;

// TaskInfo holds state information for a task that will be
// executed by a ThreadPool thread.
public ref class TaskInfo
{
public:

   // State information for the task.  These members
   // can be implemented as read-only properties, read/write
   // properties with validation, and so on, as required.
   String^ Boilerplate;
   int Value;

   // Public constructor provides an easy way to supply all
   // the information needed for the task.
   TaskInfo( String^ text, int number )
   {
      Boilerplate = text;
      Value = number;
   }

};

public ref struct Example
{
public:

   // The thread procedure performs the independent task, in this case
   // formatting and printing a very simple report.
   //
   static void ThreadProc( Object^ stateInfo )
   {
      TaskInfo^ ti = dynamic_cast<TaskInfo^>(stateInfo);
      Console::WriteLine( ti->Boilerplate, ti->Value );
   }

};

void main()
{
   
   // Create an object containing the information needed
   // for the task.
   TaskInfo^ ti = gcnew TaskInfo( "This report displays the number {0}.",42 );
   
   // Queue the task and data.
   ThreadPool::QueueUserWorkItem( gcnew WaitCallback( Example::ThreadProc ), ti );

   Console::WriteLine( "Main thread does some work, then sleeps." );
      
   // If you comment out the Sleep, the main thread exits before
   // the ThreadPool task has a chance to run.  ThreadPool uses 
   // background threads, which do not keep the application 
   // running.  (This is a simple example of a race condition.)
   Thread::Sleep( 1000 );
   Console::WriteLine( "Main thread exits." );
}
// The example displays output like the following:
//       Main thread does some work, then sleeps.
//       This report displays the number 42.
//       Main thread exits.
// This example shows how to create an object containing task
// information, and pass that object to a task queued for
// execution by the thread pool.
using System;
using System.Threading;

// TaskInfo holds state information for a task that will be
// executed by a ThreadPool thread.
public class TaskInfo 
    {
    // State information for the task.  These members
    // can be implemented as read-only properties, read/write
    // properties with validation, and so on, as required.
    public string Boilerplate;
    public int Value;

    // Public constructor provides an easy way to supply all
    // the information needed for the task.
    public TaskInfo(string text, int number) {
        Boilerplate = text;
        Value = number;
    }
}

public class Example {
    public static void Main()
    {
        // Create an object containing the information needed
        // for the task.
        TaskInfo ti = new TaskInfo("This report displays the number {0}.", 42);

        // Queue the task and data.
        ThreadPool.QueueUserWorkItem(new WaitCallback(ThreadProc), ti);

        Console.WriteLine("Main thread does some work, then sleeps.");

        // If you comment out the Sleep, the main thread exits before
        // the ThreadPool task has a chance to run.  ThreadPool uses 
        // background threads, which do not keep the application 
        // running.  (This is a simple example of a race condition.)
        Thread.Sleep(1000);

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

    // The thread procedure performs the independent task, in this case
    // formatting and printing a very simple report.
    //
    static void ThreadProc(Object stateInfo) 
    {
        TaskInfo ti = (TaskInfo) stateInfo;
        Console.WriteLine(ti.Boilerplate, ti.Value); 
    }
}
// The example displays output like the following:
//       Main thread does some work, then sleeps.
//       This report displays the number 42.
//       Main thread exits.
' This example shows how to create an object containing task
' information, and pass that object to a task queued for
' execution by the thread pool.
Imports System
Imports System.Threading
' TaskInfo holds state information for a task that will be
' executed by a ThreadPool thread.
Public Class TaskInfo
    ' State information for the task.  These members
    ' can be implemented as read-only properties, read/write
    ' properties with validation, and so on, as required.
    Public Boilerplate As String
    Public Value As Integer

    ' Public constructor provides an easy way to supply all
    ' the information needed for the task.
    Public Sub New(text As String, number As Integer)
        Boilerplate = text
        Value = number
    End Sub
End Class

Public Class Example

    <MTAThread> _
    Public Shared Sub Main()
        ' Create an object containing the information needed
        ' for the task.
        Dim ti As New TaskInfo("This report displays the number {0}.", 42)

        ' Queue the task and data.
        ThreadPool.QueueUserWorkItem( _
                New WaitCallback(AddressOf ThreadProc), ti)
        
        Console.WriteLine("Main thread does some work, then sleeps.")

        ' If you comment out the Sleep, the main thread exits before
        ' the ThreadPool task has a chance to run.  ThreadPool uses 
        ' background threads, which do not keep the application 
        ' running.  (This is a simple example of a race condition.)
        Thread.Sleep(1000)

        Console.WriteLine("Main thread exits.")
    End Sub

    ' The thread procedure performs the independent task, in this case
    ' formatting and printing a very simple report.
    '
    Shared Sub ThreadProc(stateInfo As Object)
        Dim ti As TaskInfo = CType(stateInfo, TaskInfo)
        Console.WriteLine(ti.Boilerplate, ti.Value)
    End Sub
End Class
' The example displays output like the following:
'        Main thread does some work, then sleeps.
'        This report displays the number 42.
'        Main thread exits.

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.

Version Information

In the .NET Framework version 2.0, the Thread.CurrentPrincipal property value is propagated to worker threads queued using the QueueUserWorkItem method. In earlier versions, the principal information is not propagated.