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, 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
Parameters
An object containing data to be used by the method.
Returnstrue
if the method is successfully queued; NotSupportedException is thrown if the work item could not be queued.
The common language runtime (CLR) is hosted, and the host does not support this action.
ExamplesThe following example uses the .NET thread pool to calculate the Fibonacci
result for five numbers between 20 and 40. Each Fibonacci
result is represented by the Fibonacci
class, which provides a method named ThreadPoolCallback
that performs the calculation. 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.
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. That is why each Fibonacci
object is passed an instance of the ManualResetEvent class during construction. 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. The Main
method then displays each Fibonacci
result.
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
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4