ThreadPool.QueueUserWorkItem Método

Definición

Pone en cola un método para su ejecución. El método se ejecuta cuando hay disponible un subproceso de grupo de subprocesos.

Sobrecargas

QueueUserWorkItem(WaitCallback)

Pone en cola un método para su ejecución. El método se ejecuta cuando hay disponible un subproceso de grupo de subprocesos.

QueueUserWorkItem(WaitCallback, Object)

Pone un método en cola para su ejecución y especifica un objeto que contiene los datos que debe usar el método. El método se ejecuta cuando hay disponible un subproceso de grupo de subprocesos.

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

Pone un método en cola para su ejecución especificado por un delegado de Action<T> y proporciona los datos que debe usar el método. El método se ejecuta cuando hay disponible un subproceso de grupo de subprocesos.

QueueUserWorkItem(WaitCallback)

Pone en cola un método para su ejecución. El método se ejecuta cuando hay disponible un subproceso de grupo de subprocesos.

public:
 static bool QueueUserWorkItem(System::Threading::WaitCallback ^ callBack);
public static bool QueueUserWorkItem (System.Threading.WaitCallback callBack);
static member QueueUserWorkItem : System.Threading.WaitCallback -> bool
Public Shared Function QueueUserWorkItem (callBack As WaitCallback) As Boolean

Parámetros

callBack
WaitCallback

WaitCallback que representa el método que se va a ejecutar.

Devoluciones

true si el método se pone en la cola correctamente; se produce la excepción NotSupportedException si no se puede poner en la cola el elemento de trabajo.

Excepciones

callBack es null.

Common Language Runtime (CLR) está en un host y el host no admite esta acción.

Ejemplos

En el ejemplo siguiente se usa la sobrecarga del QueueUserWorkItem(WaitCallback) método para poner en cola una tarea, representada por el ThreadProc método , para ejecutarse cuando un subproceso esté disponible. No se proporciona información de tareas con esta sobrecarga. Por lo tanto, la información que está disponible para el ThreadProc método se limita al objeto al que pertenece el método.

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.

Comentarios

Puede colocar los datos requeridos por el método en cola en los campos de instancia de la clase en la que se define el método, o bien puede usar la QueueUserWorkItem(WaitCallback, Object) sobrecarga que acepta un objeto que contiene los datos necesarios.

Nota

Los usuarios de Visual Basic pueden omitir el WaitCallback constructor y simplemente usar el AddressOf operador al pasar el método de devolución de llamada a QueueUserWorkItem. Visual Basic llama automáticamente al constructor delegado correcto.

El Thread.CurrentPrincipal valor de propiedad se propaga a subprocesos de trabajo en cola mediante el QueueUserWorkItem método .

Consulte también

Se aplica a

QueueUserWorkItem(WaitCallback, Object)

Pone un método en cola para su ejecución y especifica un objeto que contiene los datos que debe usar el método. El método se ejecuta cuando hay disponible un subproceso de grupo de subprocesos.

public:
 static bool QueueUserWorkItem(System::Threading::WaitCallback ^ callBack, System::Object ^ state);
public static bool QueueUserWorkItem (System.Threading.WaitCallback callBack, object? state);
public static bool QueueUserWorkItem (System.Threading.WaitCallback callBack, object state);
static member QueueUserWorkItem : System.Threading.WaitCallback * obj -> bool
Public Shared Function QueueUserWorkItem (callBack As WaitCallback, state As Object) As Boolean

Parámetros

callBack
WaitCallback

WaitCallback que representa el método que se va a ejecutar.

state
Object

Objeto que contiene los datos que va a usar el método.

Devoluciones

true si el método se pone en la cola correctamente; se produce la excepción NotSupportedException si no se puede poner en la cola el elemento de trabajo.

Excepciones

Common Language Runtime (CLR) está en un host y el host no admite esta acción.

callBack es null.

Ejemplos

En el ejemplo siguiente se usa el grupo de subprocesos de .NET para calcular el Fibonacci resultado de cinco números entre 20 y 40. Cada resultado de Fibonacci se representa mediante la clase Fibonacci, que proporciona un método denominado ThreadPoolCallback que realiza el cálculo. Se crea un objeto que representa cada valor de Fibonacci y el método ThreadPoolCallback se pasa a QueueUserWorkItem, que asigna un subproceso disponible en el grupo para ejecutar el método.

Dado que a cada Fibonacci objeto se le asigna un valor semialeato para calcular y, dado que cada subproceso competirá por el tiempo del procesador, no puede saber con antelación cuánto tiempo tardarán en calcularse los cinco resultados. Por eso se pasa a cada objeto Fibonacci una instancia de la clase ManualResetEvent durante la construcción. Cada objeto señala al objeto de evento proporcionado cuando se completa su cálculo, lo que permite que el subproceso principal bloquee la ejecución con WaitAll hasta que los cinco Fibonacci objetos hayan calculado un resultado. El método Main muestra entonces cada resultado de Fibonacci.

using namespace System;
using namespace System::Threading;

public ref class Fibonacci
{
private:
    ManualResetEvent^ _doneEvent;

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

public:
    
    int ID;
    int N;
    int FibOfN;

    Fibonacci(int id, int n, ManualResetEvent^ doneEvent)
    {
        ID = id;
        N = n;
        _doneEvent = doneEvent;
    }

    void Calculate()
    {
        FibOfN = Calculate(N);
    }

    void SetDone()
    {
        _doneEvent->Set();
    }
};

public ref struct Example
{
public:

    static void ThreadProc(Object^ stateInfo)
    {
        Fibonacci^ f = dynamic_cast<Fibonacci^>(stateInfo);
        Console::WriteLine("Thread {0} started...", f->ID);
        f->Calculate();
        Console::WriteLine("Thread {0} result calculated...", f->ID);
        f->SetDone();
    }
};


void main()
{
    const int FibonacciCalculations = 5;

    array<ManualResetEvent^>^ doneEvents = gcnew array<ManualResetEvent^>(FibonacciCalculations);
    array<Fibonacci^>^ fibArray = gcnew array<Fibonacci^>(FibonacciCalculations);
    Random^ rand = gcnew Random();

    Console::WriteLine("Launching {0} tasks...", FibonacciCalculations);

    for (int i = 0; i < FibonacciCalculations; i++)
    {
        doneEvents[i] = gcnew ManualResetEvent(false);
        Fibonacci^ f = gcnew Fibonacci(i, rand->Next(20, 40), doneEvents[i]);
        fibArray[i] = f;
        ThreadPool::QueueUserWorkItem(gcnew WaitCallback(Example::ThreadProc), f);
    }

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

    for (int i = 0; i < FibonacciCalculations; i++)
    {
        Fibonacci^ f = fibArray[i];
        Console::WriteLine("Fibonacci({0}) = {1}", f->N, f->FibOfN);
    }
}
// Output is similar to:
// Launching 5 tasks...
// Thread 3 started...
// Thread 2 started...
// Thread 1 started...
// Thread 0 started...
// Thread 4 started...
// Thread 4 result calculated...
// Thread 1 result calculated...
// Thread 2 result calculated...
// Thread 0 result calculated...
// Thread 3 result calculated...
// All calculations are complete.
// Fibonacci(30) = 832040
// Fibonacci(24) = 46368
// Fibonacci(26) = 121393
// Fibonacci(36) = 14930352
// Fibonacci(20) = 6765
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
Imports System.Threading

Public Class Fibonacci
    Private _doneEvent As ManualResetEvent

    Public Sub New(n As Integer, doneEvent As ManualResetEvent)
        Me.N = n
        _doneEvent = doneEvent
    End Sub

    Public ReadOnly Property N As Integer
    Public Property FibOfN As Integer

    Public Sub ThreadPoolCallback(threadContext As Object)
        Dim threadIndex As Integer = CType(threadContext, Integer)
        Console.WriteLine($"Thread {threadIndex} started...")
        FibOfN = Calculate(N)
        Console.WriteLine($"Thread {threadIndex} result calculated...")
        _doneEvent.Set()
    End Sub

    Public Function Calculate(n As Integer) As Integer
        If (n <= 1) Then
            Return n
        End If
        Return Calculate(n - 1) + Calculate(n - 2)
    End Function
End Class

Public Class ThreadPoolExample

    <MTAThread>
    Public Shared Sub Main()

        Const FibonacciCalculations As Integer = 5

        Dim doneEvents(FibonacciCalculations - 1) As ManualResetEvent
        Dim fibArray(FibonacciCalculations - 1) As Fibonacci
        Dim rand As Random = New Random()

        Console.WriteLine($"Launching {FibonacciCalculations} tasks...")

        For i As Integer = 0 To FibonacciCalculations - 1
            doneEvents(i) = New ManualResetEvent(False)
            Dim f As Fibonacci = New Fibonacci(rand.Next(20, 40), doneEvents(i))
            fibArray(i) = f
            ThreadPool.QueueUserWorkItem(AddressOf f.ThreadPoolCallback, i)
        Next

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

        For i As Integer = 0 To FibonacciCalculations - 1
            Dim f As Fibonacci = fibArray(i)
            Console.WriteLine($"Fibonacci({f.N}) = {f.FibOfN}")
        Next
    End Sub
End Class
' Output is similar to
' Launching 5 tasks...
' Thread 1 started...
' Thread 2 started...
' Thread 3 started...
' Thread 4 started...
' Thread 0 started...
' Thread 4 result calculated...
' Thread 2 result calculated...
' Thread 3 result calculated...
' Thread 0 result calculated...
' Thread 1 result calculated...
' All calculations are complete.
' Fibonacci(37) = 24157817
' Fibonacci(38) = 39088169
' Fibonacci(29) = 514229
' Fibonacci(32) = 2178309
' Fibonacci(23) = 28657

Comentarios

Si el método de devolución de llamada requiere datos complejos, puede definir una clase para que contenga los datos.

Nota

Los usuarios de Visual Basic pueden omitir el WaitCallback constructor y simplemente usar el AddressOf operador al pasar el método de devolución de llamada a QueueUserWorkItem. Visual Basic llama automáticamente al constructor delegado correcto.

Consulte también

Se aplica a

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

Pone un método en cola para su ejecución especificado por un delegado de Action<T> y proporciona los datos que debe usar el método. El método se ejecuta cuando hay disponible un subproceso de grupo de subprocesos.

public:
generic <typename TState>
 static bool QueueUserWorkItem(Action<TState> ^ callBack, TState state, bool preferLocal);
public static bool QueueUserWorkItem<TState> (Action<TState> callBack, TState state, bool preferLocal);
static member QueueUserWorkItem : Action<'State> * 'State * bool -> bool
Public Shared Function QueueUserWorkItem(Of TState) (callBack As Action(Of TState), state As TState, preferLocal As Boolean) As Boolean

Parámetros de tipo

TState

Tipo de elementos de state.

Parámetros

callBack
Action<TState>

Action<T> que representa el método que se va a ejecutar.

state
TState

Objeto que contiene los datos que va a usar el método.

preferLocal
Boolean

true si se prefiere poner en cola el elemento de trabajo en una cola junto al subproceso actual; false si se prefiere poner en cola el elemento de trabajo en la cola compartida del grupo de subprocesos.

Devoluciones

true si el método se pone en la cola correctamente; se produce la excepción NotSupportedException si no se puede poner en la cola el elemento de trabajo.

Se aplica a