ThreadPool.QueueUserWorkItem 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
將方法排入佇列,以等候執行。 可以使用執行緒集區執行緒時,即可執行這個方法。
多載
QueueUserWorkItem(WaitCallback) |
將方法排入佇列,以等候執行。 可以使用執行緒集區執行緒時,即可執行這個方法。 |
QueueUserWorkItem(WaitCallback, Object) |
將方法排入佇列,以等候執行,並指定包含這個方法所要使用之資料的物件。 可以使用執行緒集區執行緒時,即可執行這個方法。 |
QueueUserWorkItem<TState>(Action<TState>, TState, Boolean) |
將 Action<T> 委派指定的方法排入佇列以便執行,並提供將由方法使用的資料。 可以使用執行緒集區執行緒時,即可執行這個方法。 |
QueueUserWorkItem(WaitCallback)
將方法排入佇列,以等候執行。 可以使用執行緒集區執行緒時,即可執行這個方法。
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
參數
- callBack
- WaitCallback
WaitCallback,代表要執行的方法。
傳回
如果方法成功佇列則為 true
;如果工作項目無法佇列則會擲回 NotSupportedException。
例外狀況
callBack
為 null
。
Common Language Runtime (CLR) 已裝載,而且主機不支援這個動作。
範例
下列範例會 QueueUserWorkItem(WaitCallback) 使用 方法多載,將方法表示 ThreadProc
的工作排入佇列,以在線程可用時執行。 此多載未提供任何工作資訊。 因此,方法可用的 ThreadProc
資訊僅限於方法所屬的物件。
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.
備註
您可以將佇列方法所需的數據放在定義方法的 類別實例欄位中,或使用 QueueUserWorkItem(WaitCallback, Object) 接受包含必要數據之物件的多載。
注意
Visual Basic 使用者可以省略建WaitCallback構函式,只要在將回呼方法傳遞至 QueueUserWorkItem時使用 AddressOf
運算符即可。 Visual Basic 會自動呼叫正確的委派建構函式。
Thread.CurrentPrincipal屬性值會傳播至使用 QueueUserWorkItem 方法排入佇列的背景工作線程。
另請參閱
適用於
QueueUserWorkItem(WaitCallback, Object)
將方法排入佇列,以等候執行,並指定包含這個方法所要使用之資料的物件。 可以使用執行緒集區執行緒時,即可執行這個方法。
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
參數
- callBack
- WaitCallback
WaitCallback,代表要執行的方法。
- state
- Object
物件,包含這個方法所要使用的資料。
傳回
如果方法成功佇列則為 true
;如果工作項目無法佇列則會擲回 NotSupportedException。
例外狀況
Common Language Runtime (CLR) 已裝載,而且主機不支援這個動作。
callBack
為 null
。
範例
下列範例會使用 .NET 線程集區來計算 Fibonacci
五個介於 20 到 40 之間的數字結果。 每個 Fibonacci
結果都會以 Fibonacci
類別表示,該類別提供一個執行計算的方法,稱為 ThreadPoolCallback
。 這會建立代表每個 Fibonacci
值的物件,並將 ThreadPoolCallback
方法傳遞至 QueueUserWorkItem,以指派集區中的可用執行緒來執行此方法。
因為每個 Fibonacci
物件都有半隨機值來計算,而且因為每個線程都會競爭處理器時間,所以您無法事先知道計算所有五個結果所需的時間。 這就是為什麼會在建構期間將每個 Fibonacci
物件傳遞至 ManualResetEvent 類別的執行個體。 當計算完成時,每個物件都會發出所提供事件對象的訊號,這可讓主要線程封鎖執行 WaitAll ,直到所有五 Fibonacci
個物件都計算出結果為止。
Main
方法接著會顯示每個 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
備註
如果回呼方法需要複雜的數據,您可以定義類別以包含數據。
注意
Visual Basic 使用者可以省略建WaitCallback構函式,只要在將回呼方法傳遞至 QueueUserWorkItem時使用 AddressOf
運算符即可。 Visual Basic 會自動呼叫正確的委派建構函式。
另請參閱
適用於
QueueUserWorkItem<TState>(Action<TState>, TState, Boolean)
將 Action<T> 委派指定的方法排入佇列以便執行,並提供將由方法使用的資料。 可以使用執行緒集區執行緒時,即可執行這個方法。
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
類型參數
- TState
state
項目的類型。
參數
- state
- TState
物件,包含這個方法所要使用的資料。
- preferLocal
- Boolean
true
以偏好將佇列中工作項目排入接近目前執行緒的佇列;false
以偏好將工作項目排入執行緒集區的共用佇列。
傳回
如果方法成功佇列則為 true
;如果工作項目無法佇列則會擲回 NotSupportedException。