ThreadPool.QueueUserWorkItem ThreadPool.QueueUserWorkItem ThreadPool.QueueUserWorkItem ThreadPool.QueueUserWorkItem Method

Definizione

Accoda un metodo da eseguire.Queues a method for execution. Il metodo viene eseguito quando un thread del pool di thread diventa disponibile.The method executes when a thread pool thread becomes available.

Overload

QueueUserWorkItem(WaitCallback) QueueUserWorkItem(WaitCallback) QueueUserWorkItem(WaitCallback) QueueUserWorkItem(WaitCallback)

Accoda un metodo da eseguire.Queues a method for execution. Il metodo viene eseguito quando un thread del pool di thread diventa disponibile.The method executes when a thread pool thread becomes available.

QueueUserWorkItem(WaitCallback, Object) QueueUserWorkItem(WaitCallback, Object) QueueUserWorkItem(WaitCallback, Object) QueueUserWorkItem(WaitCallback, Object)

Accoda un metodo da eseguire e specifica un oggetto che contiene i dati che dovranno essere usati dal metodo.Queues a method for execution, and specifies an object containing data to be used by the method. Il metodo viene eseguito quando un thread del pool di thread diventa disponibile.The method executes when a thread pool thread becomes available.

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

Accoda un metodo specificato da un delegato Action<T> per l'esecuzione e fornisce i dati che devono essere usati dal metodo.Queues a method specified by an Action<T> delegate for execution, and provides data to be used by the method. Il metodo viene eseguito quando un thread del pool di thread diventa disponibile.The method executes when a thread pool thread becomes available.

QueueUserWorkItem(WaitCallback) QueueUserWorkItem(WaitCallback) QueueUserWorkItem(WaitCallback) QueueUserWorkItem(WaitCallback)

Accoda un metodo da eseguire.Queues a method for execution. Il metodo viene eseguito quando un thread del pool di thread diventa disponibile.The method executes when a thread pool thread becomes available.

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

Parametri

callBack
WaitCallback WaitCallback WaitCallback WaitCallback

Oggetto WaitCallback che rappresenta il metodo da eseguire.A WaitCallback that represents the method to be executed.

Restituisce

true se il metodo viene accodato correttamente. Viene generata l'eccezione NotSupportedException se non è stato possibile accodare l'elemento di lavoro.true if the method is successfully queued; NotSupportedException is thrown if the work item could not be queued.

Eccezioni

Common Language Runtime (CLR) è ospitato e l'host non supporta questa azione.The common language runtime (CLR) is hosted, and the host does not support this action.

Esempi

L'esempio seguente usa il QueueUserWorkItem(WaitCallback) overload del metodo per accodare un'attività, che è rappresentato dal ThreadProc metodo, da eseguire quando un thread diventa disponibile.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. Nessuna informazione di attività viene fornita con questo overload.No task information is supplied with this overload. Di conseguenza, le informazioni che sono disponibile per il ThreadProc metodo è limitato all'oggetto al quale appartiene il metodo.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.

Commenti

È possibile inserire i dati necessari per il metodo in coda i campi di istanza della classe in cui il metodo è definito o è possibile usare il QueueUserWorkItem(WaitCallback, Object) overload che accetta un oggetto che contiene i dati necessari.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.

Nota

Gli utenti di Visual Basic è possono omettere il WaitCallback costruttore e usare semplicemente il AddressOf operatore quando si passa il metodo di callback per QueueUserWorkItem.Visual Basic users can omit the WaitCallback constructor, and simply use the AddressOf operator when passing the callback method to QueueUserWorkItem. Visual Basic chiama automaticamente il costruttore di delegato corretto.Visual Basic automatically calls the correct delegate constructor.

Informazioni sulla versioneVersion Information

In .NET Framework versione 2.0, il Thread.CurrentPrincipal valore della proprietà viene propagato al thread di lavoro in coda tramite il QueueUserWorkItem (metodo).In the .NET Framework version 2.0, the Thread.CurrentPrincipal property value is propagated to worker threads queued using the QueueUserWorkItem method. Nelle versioni precedenti, le informazioni dell'entità non viene propagate.In earlier versions, the principal information is not propagated.

Vedi anche

QueueUserWorkItem(WaitCallback, Object) QueueUserWorkItem(WaitCallback, Object) QueueUserWorkItem(WaitCallback, Object) QueueUserWorkItem(WaitCallback, Object)

Accoda un metodo da eseguire e specifica un oggetto che contiene i dati che dovranno essere usati dal metodo.Queues a method for execution, and specifies an object containing data to be used by the method. Il metodo viene eseguito quando un thread del pool di thread diventa disponibile.The method executes when a thread pool thread becomes available.

public:
 static bool QueueUserWorkItem(System::Threading::WaitCallback ^ callBack, System::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

Parametri

callBack
WaitCallback WaitCallback WaitCallback WaitCallback

WaitCallback che rappresenta il metodo da eseguire.A WaitCallback representing the method to execute.

state
Object Object Object Object

Oggetto contenente i dati che devono essere usati dal metodo.An object containing data to be used by the method.

Restituisce

true se il metodo viene accodato correttamente. Viene generata l'eccezione NotSupportedException se non è stato possibile accodare l'elemento di lavoro.true if the method is successfully queued; NotSupportedException is thrown if the work item could not be queued.

Eccezioni

Common Language Runtime (CLR) è ospitato e l'host non supporta questa azione.The common language runtime (CLR) is hosted, and the host does not support this action.

Esempi

L'esempio seguente usa il pool di thread .NET per la quale calcolare il Fibonacci risultato per cinque numeri compresi tra 20 e 40.The following example uses the .NET thread pool to calculate the Fibonacci result for five numbers between 20 and 40. Ogni risultato di Fibonacci viene rappresentato dalla classe Fibonacci, che fornisce un metodo denominato ThreadPoolCallback per l'esecuzione del calcolo.Each Fibonacci result is represented by the Fibonacci class, which provides a method named ThreadPoolCallback that performs the calculation. Viene creato un oggetto che rappresenta ogni valore Fibonacci, il metodo ThreadPoolCallback viene passato a QueueUserWorkItem, che assegna un thread disponibile del pool per eseguire il metodo.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.

Poiché ogni Fibonacci oggetto viene assegnato un valore semi-casuale da calcolare e poiché ogni thread sarà in competizione per il tempo del processore, non è possibile sapere in anticipo quanto tempo impiegherà per tutti i cinque risultati deve essere calcolato.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. Per questo motivo a ogni oggetto Fibonacci viene passata un'istanza della classe ManualResetEvent durante la costruzione.That is why each Fibonacci object is passed an instance of the ManualResetEvent class during construction. Ogni oggetto segnala l'oggetto evento fornito quando cui il calcolo viene completato, che consente al thread primario può bloccare l'esecuzione con WaitAll finché tutti e cinque Fibonacci gli oggetti hanno calcolato un risultato.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. Il metodo Main visualizza quindi ogni risultato Fibonacci.The Main method then displays each Fibonacci result.

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

Commenti

Se il metodo di callback sono necessari dati complessi, è possibile definire una classe per contenere i dati.If the callback method requires complex data, you can define a class to contain the data.

Nota

Gli utenti di Visual Basic è possono omettere il WaitCallback costruttore e usare semplicemente il AddressOf operatore quando si passa il metodo di callback per QueueUserWorkItem.Visual Basic users can omit the WaitCallback constructor, and simply use the AddressOf operator when passing the callback method to QueueUserWorkItem. Visual Basic chiama automaticamente il costruttore di delegato corretto.Visual Basic automatically calls the correct delegate constructor.

Informazioni sulla versioneVersion Information

In .NET Framework versione 2.0, il Thread.CurrentPrincipal valore della proprietà viene propagato al thread di lavoro in coda tramite il QueueUserWorkItem (metodo).In the .NET Framework version 2.0, the Thread.CurrentPrincipal property value is propagated to worker threads queued using the QueueUserWorkItem method. Nelle versioni precedenti, le informazioni dell'entità non viene propagate.In earlier versions, the principal information is not propagated.

Vedi anche

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

Accoda un metodo specificato da un delegato Action<T> per l'esecuzione e fornisce i dati che devono essere usati dal metodo.Queues a method specified by an Action<T> delegate for execution, and provides data to be used by the method. Il metodo viene eseguito quando un thread del pool di thread diventa disponibile.The method executes when a thread pool thread becomes available.

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

Parametri di tipo

TState

Tipo degli elementi di state.The type of elements of state.

Parametri

callBack
Action<TState>

Action<T> che rappresenta il metodo da eseguire.An Action<T> representing the method to execute.

state

Oggetto contenente i dati che devono essere usati dal metodo.An object containing data to be used by the method.

preferLocal
Boolean Boolean Boolean Boolean

Diversamente dagli altri metodi QueueUserWorkItem, preferire l'esecuzione nel pool di thread locale e non nel pool di thread globale.Unlike other QueueUserWorkItem methods, prefer executing in the local thread pool and not the global thread pool.

Restituisce

true se il metodo viene accodato correttamente. Viene generata l'eccezione NotSupportedException se non è stato possibile accodare l'elemento di lavoro.true if the method is successfully queued; NotSupportedException is thrown if the work item could not be queued.

Si applica a