ThreadPool.QueueUserWorkItem 메서드

정의

실행을 위해 메서드를 큐에 대기시킵니다. 이 메서드는 스레드 풀 스레드를 사용할 수 있을 때 실행됩니다.

오버로드

QueueUserWorkItem(WaitCallback)

실행을 위해 메서드를 큐에 대기시킵니다. 이 메서드는 스레드 풀 스레드를 사용할 수 있을 때 실행됩니다.

QueueUserWorkItem(WaitCallback, Object)

실행을 위해 메서드를 큐에 대기시키고 메서드에서 사용할 데이터가 들어 있는 개체를 지정합니다. 이 메서드는 스레드 풀 스레드를 사용할 수 있을 때 실행됩니다.

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

실행을 위해 Action<T> 대리자에 의해 지정된 메서드를 큐에 대기시키고 메서드에서 사용할 데이터를 제공합니다. 이 메서드는 스레드 풀 스레드를 사용할 수 있을 때 실행됩니다.

QueueUserWorkItem(WaitCallback)

Source:
ThreadPoolWorkQueue.cs
Source:
ThreadPoolWorkQueue.cs
Source:
ThreadPoolWorkQueue.cs

실행을 위해 메서드를 큐에 대기시킵니다. 이 메서드는 스레드 풀 스레드를 사용할 수 있을 때 실행됩니다.

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이 throw됩니다.

예외

callBack이(가) null인 경우

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.

설명

큐에 대기 중인 메서드에 필요한 데이터를 메서드가 정의된 클래스의 instance 필드에 배치하거나 필요한 데이터가 포함된 개체를 허용하는 오버로드를 사용할 QueueUserWorkItem(WaitCallback, Object) 수 있습니다.

참고

Visual Basic 사용자는 생성자를 생략 WaitCallback 하고 콜백 메서드QueueUserWorkItemAddressOf 에 전달할 때 연산자를 사용할 수 있습니다. Visual Basic은 올바른 대리자 생성자를 자동으로 호출합니다.

Thread.CurrentPrincipal 속성 값은 메서드를 사용하여 큐에 대기 중인 작업자 스레드로 QueueUserWorkItem 전파됩니다.

추가 정보

적용 대상

QueueUserWorkItem(WaitCallback, Object)

Source:
ThreadPoolWorkQueue.cs
Source:
ThreadPoolWorkQueue.cs
Source:
ThreadPoolWorkQueue.cs

실행을 위해 메서드를 큐에 대기시키고 메서드에서 사용할 데이터가 들어 있는 개체를 지정합니다. 이 메서드는 스레드 풀 스레드를 사용할 수 있을 때 실행됩니다.

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이 throw됩니다.

예외

CLR(공용 언어 런타임)이 호스팅되며 호스트에서 이 작업을 지원하지 않는 경우

callBack이(가) null인 경우

예제

다음 예제에서는 .NET 스레드 풀을 사용하여 20에서 40 사이의 5개 숫자에 대한 결과를 계산 Fibonacci 합니다. 각 Fibonacci 결과는 계산을 수행하는 ThreadPoolCallback이라는 메서드를 제공하는 Fibonacci 클래스로 표현됩니다. 각 Fibonacci 값을 나타내는 개체가 생성되고 ThreadPoolCallback 메서드가 QueueUserWorkItem에 전달되면, 여기서 풀에서 사용 가능한 스레드를 할당하여 메서드를 실행합니다.

Fibonacci 개체에 계산할 반 임의 값이 부여되고 각 스레드가 프로세서 시간 동안 경쟁하기 때문에 5가지 결과를 모두 계산하는 데 걸리는 시간을 미리 알 수 없습니다. 이 때문에 생성 중 각 Fibonacci 개체에 ManualResetEvent 클래스 인스턴스가 전달됩니다. 각 개체는 계산이 완료되면 제공된 이벤트 개체에 신호를 보냅니다. 이를 통해 주 스레드는 5개의 Fibonacci 개체가 모두 결과를 계산할 때까지 를 사용하여 실행을 WaitAll 차단할 수 있습니다. 그런 다음 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 하고 콜백 메서드QueueUserWorkItemAddressOf 에 전달할 때 연산자를 사용할 수 있습니다. Visual Basic은 올바른 대리자 생성자를 자동으로 호출합니다.

추가 정보

적용 대상

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

Source:
ThreadPoolWorkQueue.cs
Source:
ThreadPoolWorkQueue.cs
Source:
ThreadPoolWorkQueue.cs

실행을 위해 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의 요소 형식입니다.

매개 변수

callBack
Action<TState>

실행할 메서드를 나타내는 Action<T>입니다.

state
TState

메서드에서 사용할 데이터가 들어 있는 개체입니다.

preferLocal
Boolean

현재 스레드에 가까운 큐에 작업 항목을 넣으려면 true이고, 스레드 풀의 공유 큐에 작업 항목을 넣으려면 false입니다.

반환

메서드가 성공적으로 큐에 대기되면 true이고, 작업 항목을 큐에 대기할 수 없으면 NotSupportedException이 throw됩니다.

적용 대상