WaitHandle.SignalAndWait 메서드

정의

WaitHandle에 신호하고 다른 신호를 기다립니다.

오버로드

SignalAndWait(WaitHandle, WaitHandle)

WaitHandle에 신호하고 다른 신호를 기다립니다.

SignalAndWait(WaitHandle, WaitHandle, Int32, Boolean)

제한 시간 간격을 부호 있는 32비트 정수로 지정하고 대기 상태로 들어가기 전에 컨텍스트에 대한 동기화 도메인을 종료할지 여부를 지정하여, WaitHandle 중 하나에게 알리고 다음을 기다립니다.

SignalAndWait(WaitHandle, WaitHandle, TimeSpan, Boolean)

제한 시간 간격을 TimeSpan으로 지정하고 대기 상태로 들어가기 전에 컨텍스트에 대한 동기화 도메인을 종료할지 여부를 지정하여, WaitHandle 중 하나에게 알리고 다음을 기다립니다.

SignalAndWait(WaitHandle, WaitHandle)

Source:
WaitHandle.cs
Source:
WaitHandle.cs
Source:
WaitHandle.cs

WaitHandle에 신호하고 다른 신호를 기다립니다.

public:
 static bool SignalAndWait(System::Threading::WaitHandle ^ toSignal, System::Threading::WaitHandle ^ toWaitOn);
public static bool SignalAndWait (System.Threading.WaitHandle toSignal, System.Threading.WaitHandle toWaitOn);
static member SignalAndWait : System.Threading.WaitHandle * System.Threading.WaitHandle -> bool
Public Shared Function SignalAndWait (toSignal As WaitHandle, toWaitOn As WaitHandle) As Boolean

매개 변수

toSignal
WaitHandle

신호를 보낼 WaitHandle입니다.

toWaitOn
WaitHandle

대기할 WaitHandle입니다.

반환

신호를 보내는 작업과 대기가 모두 성공적으로 완료되면 true를 반환하고, 대기가 완료되지 않으면 아무 값도 반환되지 않습니다.

예외

toSignal이(가) null인 경우

또는

toWaitOn이(가) null인 경우

STA 상태의 스레드에서 메서드가 호출된 경우

toSignal이 세마포이며 이미 최대 카운트에 도달한 경우

스레드가 뮤텍스를 해제하지 않고 종료되었으므로 대기가 완료되었습니다.

예제

다음 코드 예제에서는 메서드 오버로드를 사용하여 SignalAndWait(WaitHandle, WaitHandle) 기본 스레드가 차단된 스레드에 신호를 보냅니다. 그런 다음 스레드가 작업을 완료할 때까지 기다립니다.

이 예제에서는 5개의 스레드를 시작하고 플래그를 사용하여 만든 EventResetMode.AutoReset 스레드를 EventWaitHandle 차단한 다음 사용자가 ENTER 키를 누를 때마다 하나의 스레드를 해제합니다. 그런 다음, 이 예제에서는 다른 5개의 스레드를 큐에 대기시키고 플래그를 사용하여 만든 EventResetMode.ManualResetEventWaitHandle 사용하여 모두 해제합니다.

using namespace System;
using namespace System::Threading;

public ref class Example
{
private:
   // The EventWaitHandle used to demonstrate the difference
   // between AutoReset and ManualReset synchronization events.
   //
   static EventWaitHandle^ ewh;

   // A counter to make sure all threads are started and
   // blocked before any are released. A Long is used to show
   // the use of the 64-bit Interlocked methods.
   //
   static __int64 threadCount = 0;

   // An AutoReset event that allows the main thread to block
   // until an exiting thread has decremented the count.
   //
   static EventWaitHandle^ clearCount =
      gcnew EventWaitHandle( false,EventResetMode::AutoReset );

public:
   [MTAThread]
   static void main()
   {
      // Create an AutoReset EventWaitHandle.
      //
      ewh = gcnew EventWaitHandle( false,EventResetMode::AutoReset );
      
      // Create and start five numbered threads. Use the
      // ParameterizedThreadStart delegate, so the thread
      // number can be passed as an argument to the Start
      // method.
      for ( int i = 0; i <= 4; i++ )
      {
         Thread^ t = gcnew Thread(
            gcnew ParameterizedThreadStart( ThreadProc ) );
         t->Start( i );
      }
      
      // Wait until all the threads have started and blocked.
      // When multiple threads use a 64-bit value on a 32-bit
      // system, you must access the value through the
      // Interlocked class to guarantee thread safety.
      //
      while ( Interlocked::Read( threadCount ) < 5 )
      {
         Thread::Sleep( 500 );
      }

      // Release one thread each time the user presses ENTER,
      // until all threads have been released.
      //
      while ( Interlocked::Read( threadCount ) > 0 )
      {
         Console::WriteLine( L"Press ENTER to release a waiting thread." );
         Console::ReadLine();
         
         // SignalAndWait signals the EventWaitHandle, which
         // releases exactly one thread before resetting,
         // because it was created with AutoReset mode.
         // SignalAndWait then blocks on clearCount, to
         // allow the signaled thread to decrement the count
         // before looping again.
         //
         WaitHandle::SignalAndWait( ewh, clearCount );
      }
      Console::WriteLine();
      
      // Create a ManualReset EventWaitHandle.
      //
      ewh = gcnew EventWaitHandle( false,EventResetMode::ManualReset );
      
      // Create and start five more numbered threads.
      //
      for ( int i = 0; i <= 4; i++ )
      {
         Thread^ t = gcnew Thread(
            gcnew ParameterizedThreadStart( ThreadProc ) );
         t->Start( i );
      }
      
      // Wait until all the threads have started and blocked.
      //
      while ( Interlocked::Read( threadCount ) < 5 )
      {
         Thread::Sleep( 500 );
      }

      // Because the EventWaitHandle was created with
      // ManualReset mode, signaling it releases all the
      // waiting threads.
      //
      Console::WriteLine( L"Press ENTER to release the waiting threads." );
      Console::ReadLine();
      ewh->Set();

   }

   static void ThreadProc( Object^ data )
   {
      int index = static_cast<Int32>(data);

      Console::WriteLine( L"Thread {0} blocks.", data );
      // Increment the count of blocked threads.
      Interlocked::Increment( threadCount );
      
      // Wait on the EventWaitHandle.
      ewh->WaitOne();

      Console::WriteLine( L"Thread {0} exits.", data );
      // Decrement the count of blocked threads.
      Interlocked::Decrement( threadCount );
      
      // After signaling ewh, the main thread blocks on
      // clearCount until the signaled thread has
      // decremented the count. Signal it now.
      //
      clearCount->Set();
   }
};
using System;
using System.Threading;

public class Example
{
    // The EventWaitHandle used to demonstrate the difference
    // between AutoReset and ManualReset synchronization events.
    //
    private static EventWaitHandle ewh;

    // A counter to make sure all threads are started and
    // blocked before any are released. A Long is used to show
    // the use of the 64-bit Interlocked methods.
    //
    private static long threadCount = 0;

    // An AutoReset event that allows the main thread to block
    // until an exiting thread has decremented the count.
    //
    private static EventWaitHandle clearCount = 
        new EventWaitHandle(false, EventResetMode.AutoReset);

    [MTAThread]
    public static void Main()
    {
        // Create an AutoReset EventWaitHandle.
        //
        ewh = new EventWaitHandle(false, EventResetMode.AutoReset);

        // Create and start five numbered threads. Use the
        // ParameterizedThreadStart delegate, so the thread
        // number can be passed as an argument to the Start 
        // method.
        for (int i = 0; i <= 4; i++)
        {
            Thread t = new Thread(
                new ParameterizedThreadStart(ThreadProc)
            );
            t.Start(i);
        }

        // Wait until all the threads have started and blocked.
        // When multiple threads use a 64-bit value on a 32-bit
        // system, you must access the value through the
        // Interlocked class to guarantee thread safety.
        //
        while (Interlocked.Read(ref threadCount) < 5)
        {
            Thread.Sleep(500);
        }

        // Release one thread each time the user presses ENTER,
        // until all threads have been released.
        //
        while (Interlocked.Read(ref threadCount) > 0)
        {
            Console.WriteLine("Press ENTER to release a waiting thread.");
            Console.ReadLine();

            // SignalAndWait signals the EventWaitHandle, which
            // releases exactly one thread before resetting, 
            // because it was created with AutoReset mode. 
            // SignalAndWait then blocks on clearCount, to 
            // allow the signaled thread to decrement the count
            // before looping again.
            //
            WaitHandle.SignalAndWait(ewh, clearCount);
        }
        Console.WriteLine();

        // Create a ManualReset EventWaitHandle.
        //
        ewh = new EventWaitHandle(false, EventResetMode.ManualReset);

        // Create and start five more numbered threads.
        //
        for(int i=0; i<=4; i++)
        {
            Thread t = new Thread(
                new ParameterizedThreadStart(ThreadProc)
            );
            t.Start(i);
        }

        // Wait until all the threads have started and blocked.
        //
        while (Interlocked.Read(ref threadCount) < 5)
        {
            Thread.Sleep(500);
        }

        // Because the EventWaitHandle was created with
        // ManualReset mode, signaling it releases all the
        // waiting threads.
        //
        Console.WriteLine("Press ENTER to release the waiting threads.");
        Console.ReadLine();
        ewh.Set();
    }

    public static void ThreadProc(object data)
    {
        int index = (int) data;

        Console.WriteLine("Thread {0} blocks.", data);
        // Increment the count of blocked threads.
        Interlocked.Increment(ref threadCount);

        // Wait on the EventWaitHandle.
        ewh.WaitOne();

        Console.WriteLine("Thread {0} exits.", data);
        // Decrement the count of blocked threads.
        Interlocked.Decrement(ref threadCount);

        // After signaling ewh, the main thread blocks on
        // clearCount until the signaled thread has 
        // decremented the count. Signal it now.
        //
        clearCount.Set();
    }
}
Imports System.Threading

Public Class Example

    ' The EventWaitHandle used to demonstrate the difference
    ' between AutoReset and ManualReset synchronization events.
    '
    Private Shared ewh As EventWaitHandle

    ' A counter to make sure all threads are started and
    ' blocked before any are released. A Long is used to show
    ' the use of the 64-bit Interlocked methods.
    '
    Private Shared threadCount As Long = 0

    ' An AutoReset event that allows the main thread to block
    ' until an exiting thread has decremented the count.
    '
    Private Shared clearCount As New EventWaitHandle(False, _
        EventResetMode.AutoReset)

    <MTAThread> _
    Public Shared Sub Main()

        ' Create an AutoReset EventWaitHandle.
        '
        ewh = New EventWaitHandle(False, EventResetMode.AutoReset)

        ' Create and start five numbered threads. Use the
        ' ParameterizedThreadStart delegate, so the thread
        ' number can be passed as an argument to the Start 
        ' method.
        For i As Integer = 0 To 4
            Dim t As New Thread(AddressOf ThreadProc)
            t.Start(i)
        Next i

        ' Wait until all the threads have started and blocked.
        ' When multiple threads use a 64-bit value on a 32-bit
        ' system, you must access the value through the
        ' Interlocked class to guarantee thread safety.
        '
        While Interlocked.Read(threadCount) < 5
            Thread.Sleep(500)
        End While

        ' Release one thread each time the user presses ENTER,
        ' until all threads have been released.
        '
        While Interlocked.Read(threadCount) > 0
            Console.WriteLine("Press ENTER to release a waiting thread.")
            Console.ReadLine()

            ' SignalAndWait signals the EventWaitHandle, which
            ' releases exactly one thread before resetting, 
            ' because it was created with AutoReset mode. 
            ' SignalAndWait then blocks on clearCount, to 
            ' allow the signaled thread to decrement the count
            ' before looping again.
            '
            WaitHandle.SignalAndWait(ewh, clearCount)
        End While
        Console.WriteLine()

        ' Create a ManualReset EventWaitHandle.
        '
        ewh = New EventWaitHandle(False, EventResetMode.ManualReset)

        ' Create and start five more numbered threads.
        '
        For i As Integer = 0 To 4
            Dim t As New Thread(AddressOf ThreadProc)
            t.Start(i)
        Next i

        ' Wait until all the threads have started and blocked.
        '
        While Interlocked.Read(threadCount) < 5
            Thread.Sleep(500)
        End While

        ' Because the EventWaitHandle was created with
        ' ManualReset mode, signaling it releases all the
        ' waiting threads.
        '
        Console.WriteLine("Press ENTER to release the waiting threads.")
        Console.ReadLine()
        ewh.Set()
        
    End Sub

    Public Shared Sub ThreadProc(ByVal data As Object)
        Dim index As Integer = CInt(data)

        Console.WriteLine("Thread {0} blocks.", data)
        ' Increment the count of blocked threads.
        Interlocked.Increment(threadCount)

        ' Wait on the EventWaitHandle.
        ewh.WaitOne()

        Console.WriteLine("Thread {0} exits.", data)
        ' Decrement the count of blocked threads.
        Interlocked.Decrement(threadCount)

        ' After signaling ewh, the main thread blocks on
        ' clearCount until the signaled thread has 
        ' decremented the count. Signal it now.
        '
        clearCount.Set()
    End Sub
End Class

설명

이 연산은 원자성으로 보장되지 않습니다. 현재 스레드가 신호를 받은 toSignal 후 대기하기 전에 toWaitOn다른 프로세서에서 실행되는 스레드가 신호를 toWaitOn 표시하거나 대기할 수 있습니다.

적용 대상

SignalAndWait(WaitHandle, WaitHandle, Int32, Boolean)

Source:
WaitHandle.cs
Source:
WaitHandle.cs
Source:
WaitHandle.cs

제한 시간 간격을 부호 있는 32비트 정수로 지정하고 대기 상태로 들어가기 전에 컨텍스트에 대한 동기화 도메인을 종료할지 여부를 지정하여, WaitHandle 중 하나에게 알리고 다음을 기다립니다.

public:
 static bool SignalAndWait(System::Threading::WaitHandle ^ toSignal, System::Threading::WaitHandle ^ toWaitOn, int millisecondsTimeout, bool exitContext);
public static bool SignalAndWait (System.Threading.WaitHandle toSignal, System.Threading.WaitHandle toWaitOn, int millisecondsTimeout, bool exitContext);
static member SignalAndWait : System.Threading.WaitHandle * System.Threading.WaitHandle * int * bool -> bool
Public Shared Function SignalAndWait (toSignal As WaitHandle, toWaitOn As WaitHandle, millisecondsTimeout As Integer, exitContext As Boolean) As Boolean

매개 변수

toSignal
WaitHandle

신호를 보낼 WaitHandle입니다.

toWaitOn
WaitHandle

대기할 WaitHandle입니다.

millisecondsTimeout
Int32

대기할 간격을 나타내는 정수입니다. 값이 Infinite, 즉 -1이면 무기한 대기합니다.

exitContext
Boolean

대기 전에 컨텍스트에 대한 동기화 도메인을 종료하고(동기화된 컨텍스트에 있는 경우) 이 도메인을 다시 가져오려면 true이고, 그렇지 않으면 false입니다.

반환

신호를 보내는 작업과 대기가 모두 성공적으로 완료되면 true를 반환하고, 신호는 성공적으로 보냈으나 대기가 시간 초과되었으면 false를 반환합니다.

예외

toSignalnull입니다.

또는

toWaitOn이(가) null인 경우

STA 상태의 스레드에서 메서드가 호출되는 경우

WaitHandle에서 최대 횟수를 초과하여 신호를 받을 수 없는 경우

millisecondsTimeout이 시간 제한 없음을 나타내는 -1 이외의 음수인 경우

스레드가 뮤텍스를 해제하지 않고 종료되었으므로 대기가 완료되었습니다.

설명

이 연산은 원자성으로 보장되지 않습니다. 현재 스레드가 신호를 받은 toSignal 후 대기하기 전에 toWaitOn다른 프로세서에서 실행되는 스레드가 신호를 toWaitOn 표시하거나 대기할 수 있습니다.

가 0이면 millisecondsTimeout 메서드가 차단되지 않습니다. 의 toWaitOn 상태를 테스트하고 즉시 반환합니다.

컨텍스트 종료

exitContext 메서드가 기본이 아닌 관리되는 컨텍스트 내에서 호출되지 않는 한 매개 변수는 영향을 주지 않습니다. 스레드가 에서 ContextBoundObject파생된 클래스의 instance 대한 호출 내에 있는 경우 관리되는 컨텍스트는 기본이 아닐 수 있습니다. 와 같이 String에서 파생되지 않은 클래스에서 ContextBoundObject메서드를 현재 실행 중인 경우에도 가 현재 애플리케이션 도메인의 스택에 있는 경우 ContextBoundObject 기본이 아닌 컨텍스트에 있을 수 있습니다.

코드가 기본이 아닌 컨텍스트에서 실행되는 경우 을 지정하면 trueexitContext 이 메서드를 실행하기 전에 스레드가 기본 컨텍스트로 전환하기 위해 기본이 아닌 관리되는 컨텍스트(즉, 기본 컨텍스트로 전환)를 종료합니다. 스레드는 이 메서드에 대한 호출이 완료된 후 원래의 기본이 아닌 컨텍스트로 돌아갑니다.

컨텍스트를 종료하는 것은 컨텍스트 바인딩된 클래스에 특성이 SynchronizationAttribute 있는 경우에 유용할 수 있습니다. 이 경우 클래스의 멤버에 대한 모든 호출이 자동으로 동기화되고 동기화 도메인은 클래스의 전체 코드 본문입니다. 멤버의 호출 스택에 있는 코드가 이 메서드를 호출하고 에 를 exitContext지정 true 하는 경우 스레드는 동기화 도메인을 종료합니다. 그러면 개체의 멤버를 호출할 때 차단된 스레드를 계속 진행할 수 있습니다. 이 메서드가 반환되면 호출한 스레드가 동기화 도메인을 다시 입력하기 위해 대기해야 합니다.

적용 대상

SignalAndWait(WaitHandle, WaitHandle, TimeSpan, Boolean)

Source:
WaitHandle.cs
Source:
WaitHandle.cs
Source:
WaitHandle.cs

제한 시간 간격을 TimeSpan으로 지정하고 대기 상태로 들어가기 전에 컨텍스트에 대한 동기화 도메인을 종료할지 여부를 지정하여, WaitHandle 중 하나에게 알리고 다음을 기다립니다.

public:
 static bool SignalAndWait(System::Threading::WaitHandle ^ toSignal, System::Threading::WaitHandle ^ toWaitOn, TimeSpan timeout, bool exitContext);
public static bool SignalAndWait (System.Threading.WaitHandle toSignal, System.Threading.WaitHandle toWaitOn, TimeSpan timeout, bool exitContext);
static member SignalAndWait : System.Threading.WaitHandle * System.Threading.WaitHandle * TimeSpan * bool -> bool
Public Shared Function SignalAndWait (toSignal As WaitHandle, toWaitOn As WaitHandle, timeout As TimeSpan, exitContext As Boolean) As Boolean

매개 변수

toSignal
WaitHandle

신호를 보낼 WaitHandle입니다.

toWaitOn
WaitHandle

대기할 WaitHandle입니다.

timeout
TimeSpan

대기할 간격을 나타내는 TimeSpan입니다. 값이 -1이면 무기한 대기합니다.

exitContext
Boolean

대기 전에 컨텍스트에 대한 동기화 도메인을 종료하고(동기화된 컨텍스트에 있는 경우) 이 도메인을 다시 가져오려면 true이고, 그렇지 않으면 false입니다.

반환

신호를 보내는 작업과 대기가 모두 성공적으로 완료되면 true를 반환하고, 신호는 성공적으로 보냈으나 대기가 시간 초과되었으면 false를 반환합니다.

예외

toSignalnull입니다.

또는

toWaitOn이(가) null인 경우

STA 상태의 스레드에서 메서드가 호출된 경우

toSignal이 세마포이며 이미 최대 카운트에 도달한 경우

timeout이 -1이 아닌 밀리초 단위의 음수 시간으로 계산되는 경우

또는

timeoutInt32.MaxValue보다 큽 수 있습니다.

스레드가 뮤텍스를 해제하지 않고 종료되었으므로 대기가 완료되었습니다.

설명

이 연산은 원자성으로 보장되지 않습니다. 현재 스레드가 신호를 받은 toSignal 후 대기하기 전에 toWaitOn다른 프로세서에서 실행되는 스레드가 신호를 toWaitOn 표시하거나 대기할 수 있습니다.

timeout 최대값은 입니다 Int32.MaxValue.

가 0이면 timeout 메서드가 차단되지 않습니다. 의 toWaitOn 상태를 테스트하고 즉시 반환합니다.

컨텍스트 종료

exitContext 메서드가 기본이 아닌 관리되는 컨텍스트 내에서 호출되지 않는 한 매개 변수는 영향을 주지 않습니다. 스레드가 에서 ContextBoundObject파생된 클래스의 instance 대한 호출 내에 있는 경우 관리되는 컨텍스트는 기본이 아닐 수 있습니다. 와 같이 String에서 파생되지 않은 클래스에서 ContextBoundObject메서드를 현재 실행 중인 경우에도 가 현재 애플리케이션 도메인의 스택에 있는 경우 ContextBoundObject 기본이 아닌 컨텍스트에 있을 수 있습니다.

코드가 기본이 아닌 컨텍스트에서 실행되는 경우 을 지정하면 trueexitContext 이 메서드를 실행하기 전에 스레드가 기본 컨텍스트로 전환하기 위해 기본이 아닌 관리되는 컨텍스트(즉, 기본 컨텍스트로 전환)를 종료합니다. 스레드는 이 메서드에 대한 호출이 완료된 후 원래의 기본이 아닌 컨텍스트로 돌아갑니다.

컨텍스트를 종료하는 것은 컨텍스트 바인딩된 클래스에 특성이 SynchronizationAttribute 있는 경우에 유용할 수 있습니다. 이 경우 클래스의 멤버에 대한 모든 호출이 자동으로 동기화되고 동기화 도메인은 클래스의 전체 코드 본문입니다. 멤버의 호출 스택에 있는 코드가 이 메서드를 호출하고 에 를 exitContext지정 true 하는 경우 스레드는 동기화 도메인을 종료합니다. 그러면 개체의 멤버를 호출할 때 차단된 스레드를 계속 진행할 수 있습니다. 이 메서드가 반환되면 호출한 스레드가 동기화 도메인을 다시 입력하기 위해 대기해야 합니다.

적용 대상