EventWaitHandle Classe

Definição

Representa um evento de sincronização de thread.Represents a thread synchronization event.

public ref class EventWaitHandle : System::Threading::WaitHandle
[System.Runtime.InteropServices.ComVisible(true)]
public class EventWaitHandle : System.Threading.WaitHandle
type EventWaitHandle = class
    inherit WaitHandle
Public Class EventWaitHandle
Inherits WaitHandle
Herança
Derivado
Atributos

Exemplos

O exemplo de código a seguir usa a sobrecarga do método SignalAndWait(WaitHandle, WaitHandle) para permitir que o thread principal sinalize um thread bloqueado e, em seguida, aguarde até que o thread conclua uma tarefa.The following code example uses the SignalAndWait(WaitHandle, WaitHandle) method overload to allow the main thread to signal a blocked thread and then wait until the thread finishes a task.

O exemplo inicia cinco threads e permite que eles bloqueiem em um EventWaitHandle criado com o sinalizador EventResetMode.AutoReset e, em seguida, libera um thread cada vez que o usuário pressiona a tecla ENTER.The example starts five threads and allows them to block on an EventWaitHandle created with the EventResetMode.AutoReset flag, then releases one thread each time the user presses the ENTER key. Em seguida, o exemplo enfileira outros cinco threads e os libera usando um EventWaitHandle criado com o sinalizador EventResetMode.ManualReset.The example then queues another five threads and releases them all using an EventWaitHandle created with the EventResetMode.ManualReset flag.

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

Comentários

A classe EventWaitHandle permite que os threads se comuniquem entre si por sinalização.The EventWaitHandle class allows threads to communicate with each other by signaling. Normalmente, um ou mais threads são bloqueados em um EventWaitHandle até que um thread não bloqueado chame o método Set, liberando um ou mais dos threads bloqueados.Typically, one or more threads block on an EventWaitHandle until an unblocked thread calls the Set method, releasing one or more of the blocked threads. Um thread pode sinalizar um EventWaitHandle e, em seguida, bloqueá-lo, chamando o método de WaitHandle.SignalAndWait static (Shared no Visual Basic).A thread can signal an EventWaitHandle and then block on it, by calling the static (Shared in Visual Basic) WaitHandle.SignalAndWait method.

Observação

A classe EventWaitHandle fornece acesso a eventos de sincronização do sistema nomeados.The EventWaitHandle class provides access to named system synchronization events.

O comportamento de um EventWaitHandle que foi sinalizado depende de seu modo de redefinição.The behavior of an EventWaitHandle that has been signaled depends on its reset mode. Um EventWaitHandle criado com o sinalizador EventResetMode.AutoReset é redefinido automaticamente quando sinalizado, depois de liberar um único thread em espera.An EventWaitHandle created with the EventResetMode.AutoReset flag resets automatically when signaled, after releasing a single waiting thread. Um EventWaitHandle criado com o sinalizador EventResetMode.ManualReset permanece sinalizado até que seu método Reset seja chamado.An EventWaitHandle created with the EventResetMode.ManualReset flag remains signaled until its Reset method is called.

Os eventos de redefinição automática fornecem acesso exclusivo a um recurso.Automatic reset events provide exclusive access to a resource. Se um evento de redefinição automática for sinalizado quando não houver threads em espera, ele permanecerá sinalizado até que um thread tente esperar por ele.If an automatic reset event is signaled when no threads are waiting, it remains signaled until a thread attempts to wait on it. O evento libera o thread e redefine imediatamente, bloqueando os threads subsequentes.The event releases the thread and immediately resets, blocking subsequent threads.

Os eventos de redefinição manual são como Gates.Manual reset events are like gates. Quando o evento não é sinalizado, os threads que esperam por ele serão bloqueados.When the event is not signaled, threads that wait on it will block. Quando o evento é sinalizado, todos os threads em espera são liberados e o evento permanece sinalizado (ou seja, as esperas subsequentes não são bloqueadas) até que seu método Reset seja chamado.When the event is signaled, all waiting threads are released, and the event remains signaled (that is, subsequent waits do not block) until its Reset method is called. Os eventos de redefinição manual são úteis quando um thread deve concluir uma atividade antes que outros threads possam continuar.Manual reset events are useful when one thread must complete an activity before other threads can proceed.

EventWaitHandle objetos podem ser usados com os métodos WaitHandle.WaitAll e WaitHandle.WaitAny static(Shared em Visual Basic).EventWaitHandle objects can be used with the static(Shared in Visual Basic) WaitHandle.WaitAll and WaitHandle.WaitAny methods.

Para obter mais informações, consulte a seção interação do thread ou sinalização do artigo visão geral do primitivos de sincronização .For more information, see the Thread interaction, or signaling section of the Overview of synchronization primitives article.

Construtores

EventWaitHandle(Boolean, EventResetMode)

Inicializa uma nova instância da classe EventWaitHandle, especificando se o identificador de espera é sinalizado inicialmente e se ele redefine automática ou manualmente.Initializes a new instance of the EventWaitHandle class, specifying whether the wait handle is initially signaled, and whether it resets automatically or manually.

EventWaitHandle(Boolean, EventResetMode, String)

Inicializa uma nova instância da classe EventWaitHandle, especificando se o identificador de espera é sinalizado inicialmente se for criado como resultado dessa chamada, se ele é redefinido manual ou automaticamente e o nome de um evento de sincronização do sistema.Initializes a new instance of the EventWaitHandle class, specifying whether the wait handle is initially signaled if created as a result of this call, whether it resets automatically or manually, and the name of a system synchronization event.

EventWaitHandle(Boolean, EventResetMode, String, Boolean)

Inicializa uma nova instância da classe EventWaitHandle, especificando se o identificador de espera é sinalizado inicialmente se for criado como resultado dessa chamada, se ele é redefinido manual ou automaticamente, o nome de um evento de sincronização do sistema e uma variável booliana cujo valor após a chamada indica se o evento de sistema nomeado foi criado.Initializes a new instance of the EventWaitHandle class, specifying whether the wait handle is initially signaled if created as a result of this call, whether it resets automatically or manually, the name of a system synchronization event, and a Boolean variable whose value after the call indicates whether the named system event was created.

EventWaitHandle(Boolean, EventResetMode, String, Boolean, EventWaitHandleSecurity)

Inicializa uma nova instância da classe EventWaitHandle, especificando se o identificador de espera é sinalizado inicialmente se for criado como resultado dessa chamada, se ele é redefinido manual ou automaticamente, o nome de um evento de sincronização do sistema, uma variável booliana cujo valor após a chamada indica se o evento de sistema nomeado foi criado e a segurança de controle de acesso a ser aplicada ao evento nomeado se ele tiver sido criado.Initializes a new instance of the EventWaitHandle class, specifying whether the wait handle is initially signaled if created as a result of this call, whether it resets automatically or manually, the name of a system synchronization event, a Boolean variable whose value after the call indicates whether the named system event was created, and the access control security to be applied to the named event if it is created.

Campos

WaitTimeout

Indica que uma operação WaitAny(WaitHandle[], Int32, Boolean) atingiu o tempo limite antes que algum dos identificadores de espera fosse sinalizado.Indicates that a WaitAny(WaitHandle[], Int32, Boolean) operation timed out before any of the wait handles were signaled. Este campo é constante.This field is constant.

(Herdado de WaitHandle)

Propriedades

Handle

Obtém ou define o identificador de sistema operacional nativo.Gets or sets the native operating system handle.

(Herdado de WaitHandle)
SafeWaitHandle

Obtém ou define o identificador de sistema operacional nativo.Gets or sets the native operating system handle.

(Herdado de WaitHandle)

Métodos

Close()

Libera todos os recursos mantidos pelo WaitHandle atual.Releases all resources held by the current WaitHandle.

(Herdado de WaitHandle)
CreateObjRef(Type)

Cria um objeto que contém todas as informações relevantes necessárias para gerar um proxy usado para se comunicar com um objeto remoto.Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Herdado de MarshalByRefObject)
Dispose()

Libera todos os recursos usados pela instância atual da classe WaitHandle.Releases all resources used by the current instance of the WaitHandle class.

(Herdado de WaitHandle)
Dispose(Boolean)

Quando substituído em uma classe derivada, libera os recursos não gerenciados usados pelo WaitHandle e, opcionalmente, libera os recursos gerenciados.When overridden in a derived class, releases the unmanaged resources used by the WaitHandle, and optionally releases the managed resources.

(Herdado de WaitHandle)
Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.Determines whether the specified object is equal to the current object.

(Herdado de Object)
GetAccessControl()

Obtém um objeto EventWaitHandleSecurity que representa a segurança de controle de acesso para o evento do sistema nomeado representado pelo objeto EventWaitHandle atual.Gets an EventWaitHandleSecurity object that represents the access control security for the named system event represented by the current EventWaitHandle object.

GetHashCode()

Serve como a função de hash padrão.Serves as the default hash function.

(Herdado de Object)
GetLifetimeService()

Recupera o objeto de serviço de tempo de vida atual que controla a política de ciclo de vida para esta instância.Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Herdado de MarshalByRefObject)
GetType()

Obtém o Type da instância atual.Gets the Type of the current instance.

(Herdado de Object)
InitializeLifetimeService()

Obtém um objeto de serviço de tempo de vida para controlar a política de tempo de vida para essa instância.Obtains a lifetime service object to control the lifetime policy for this instance.

(Herdado de MarshalByRefObject)
MemberwiseClone()

Cria uma cópia superficial do Object atual.Creates a shallow copy of the current Object.

(Herdado de Object)
MemberwiseClone(Boolean)

Cria uma cópia superficial do objeto MarshalByRefObject atual.Creates a shallow copy of the current MarshalByRefObject object.

(Herdado de MarshalByRefObject)
OpenExisting(String)

Abre o evento de sincronização nomeado especificado, caso ele já exista.Opens the specified named synchronization event, if it already exists.

OpenExisting(String, EventWaitHandleRights)

Abre o evento de sincronização nomeado especificado, caso ele já exista, com o acesso de segurança desejado.Opens the specified named synchronization event, if it already exists, with the desired security access.

Reset()

Define o estado do evento como não sinalizado, fazendo com que os threads sejam bloqueados.Sets the state of the event to nonsignaled, causing threads to block.

Set()

Define o estado do evento a ser sinalizado, permitindo que um ou mais threads de espera prossigam.Sets the state of the event to signaled, allowing one or more waiting threads to proceed.

SetAccessControl(EventWaitHandleSecurity)

Define a segurança de controle de acesso para um evento do sistema nomeado.Sets the access control security for a named system event.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.Returns a string that represents the current object.

(Herdado de Object)
TryOpenExisting(String, EventWaitHandle)

Abre o evento de sincronização nomeado especificado, se ele já existir e retorna um valor que indica se a operação foi bem-sucedida.Opens the specified named synchronization event, if it already exists, and returns a value that indicates whether the operation succeeded.

TryOpenExisting(String, EventWaitHandleRights, EventWaitHandle)

Abre o evento de sincronização nomeado especificado, se ele já existir, com o acesso de segurança desejado e retorna um valor que indica se a operação foi bem-sucedida.Opens the specified named synchronization event, if it already exists, with the desired security access, and returns a value that indicates whether the operation succeeded.

WaitOne()

Bloqueia o thread atual até que o WaitHandle atual receba um sinal.Blocks the current thread until the current WaitHandle receives a signal.

(Herdado de WaitHandle)
WaitOne(Int32)

Bloqueia o thread atual até que o WaitHandle atual receba um sinal, usando um inteiro com sinal de 32 bits para especificar o intervalo de tempo em milissegundos.Blocks the current thread until the current WaitHandle receives a signal, using a 32-bit signed integer to specify the time interval in milliseconds.

(Herdado de WaitHandle)
WaitOne(Int32, Boolean)

Bloqueia o thread atual até que o WaitHandle atual receba um sinal, usando um inteiro com sinal de 32 bits para especificar o intervalo de tempo e especificar se sairá do domínio de sincronização antes da espera.Blocks the current thread until the current WaitHandle receives a signal, using a 32-bit signed integer to specify the time interval and specifying whether to exit the synchronization domain before the wait.

(Herdado de WaitHandle)
WaitOne(TimeSpan)

Bloqueia o thread atual até que a instância atual receba um sinal, usando um TimeSpan para especificar o intervalo de tempo.Blocks the current thread until the current instance receives a signal, using a TimeSpan to specify the time interval.

(Herdado de WaitHandle)
WaitOne(TimeSpan, Boolean)

Bloqueia o thread atual até que a instância atual receba um sinal, usando um TimeSpan para especificar o intervalo de tempo e especificar se sairá do domínio de sincronização antes da espera.Blocks the current thread until the current instance receives a signal, using a TimeSpan to specify the time interval and specifying whether to exit the synchronization domain before the wait.

(Herdado de WaitHandle)

Implantações explícitas de interface

IDisposable.Dispose()

Libera todos os recursos usados pelo WaitHandle.Releases all resources used by the WaitHandle.

(Herdado de WaitHandle)

Métodos de Extensão

GetAccessControl(EventWaitHandle)
SetAccessControl(EventWaitHandle, EventWaitHandleSecurity)
GetSafeWaitHandle(WaitHandle)

Obtém o identificador seguro para um identificador de espera nativo do sistema operacional.Gets the safe handle for a native operating system wait handle.

SetSafeWaitHandle(WaitHandle, SafeWaitHandle)

Define um identificador seguro para um identificador de espera do sistema operacional nativo.Sets a safe handle for a native operating system wait handle.

Aplica-se a

Acesso thread-safe

Este tipo é thread-safe.This type is thread safe.

Veja também