EventWaitHandle Construtores

Definição

Inicializa uma nova instância da classe EventWaitHandle.

Sobrecargas

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.

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.

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.

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.

EventWaitHandle(Boolean, EventResetMode)

Origem:
EventWaitHandle.cs
Origem:
EventWaitHandle.cs
Origem:
EventWaitHandle.cs

Inicializa uma nova instância da classe EventWaitHandle, especificando se o identificador de espera é sinalizado inicialmente e se ele redefine automática ou manualmente.

public:
 EventWaitHandle(bool initialState, System::Threading::EventResetMode mode);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode);
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode -> System.Threading.EventWaitHandle
Public Sub New (initialState As Boolean, mode As EventResetMode)

Parâmetros

initialState
Boolean

true para definir o estado inicial como sinalizado; false para defini-lo como não sinalizado.

mode
EventResetMode

Um dos valores EventResetMode que determina se o evento redefine automática ou manualmente.

Exceções

O valor de enumeração mode estava fora do intervalo legal.

Exemplos

O exemplo de código a seguir usa a sobrecarga de SignalAndWait(WaitHandle, WaitHandle) método para permitir que o thread main sinalize um thread bloqueado e aguarde até que o thread termine uma tarefa.

O exemplo inicia cinco threads e permite que eles bloqueiem em um EventWaitHandle criado com o EventResetMode.AutoReset sinalizador e, em seguida, libera um thread cada vez que o usuário pressiona a tecla Enter . Em seguida, o exemplo enfileira outros cinco threads e libera todos eles usando um EventWaitHandle criado com o EventResetMode.ManualReset sinalizador .

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

Se o estado inicial do evento não for atribuído, os threads que aguardarem o evento serão bloqueados. Se o estado inicial for sinalizado e o ManualReset sinalizador for especificado para mode, os threads que aguardarem o evento não serão bloqueados. Se o estado inicial for sinalizado e mode for AutoReset, o primeiro thread que aguardar o evento será liberado imediatamente, após o qual o evento será redefinido e os threads subsequentes serão bloqueados.

Confira também

Aplica-se a

EventWaitHandle(Boolean, EventResetMode, String)

Origem:
EventWaitHandle.cs
Origem:
EventWaitHandle.cs
Origem:
EventWaitHandle.cs

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.

public:
 EventWaitHandle(bool initialState, System::Threading::EventResetMode mode, System::String ^ name);
[System.Security.SecurityCritical]
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string? name);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name);
[<System.Security.SecurityCritical>]
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string -> System.Threading.EventWaitHandle
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string -> System.Threading.EventWaitHandle
Public Sub New (initialState As Boolean, mode As EventResetMode, name As String)

Parâmetros

initialState
Boolean

true para definir o estado inicial como sinalizado se o evento nomeado for criado como resultado dessa chamada, false para defini-lo como não sinalizado.

mode
EventResetMode

Um dos valores EventResetMode que determina se o evento redefine automática ou manualmente.

name
String

O nome, se o objeto de sincronização deve ser compartilhado com outros processos; caso contrário, null ou uma cadeia de caracteres vazia. O nome diferencia maiúsculas de minúsculas. O caractere de barra invertida (\) é reservado e só pode ser usado para especificar um namespace. Para obter mais informações sobre namespaces, consulte a seção comentários. Pode haver mais restrições sobre o nome, dependendo do sistema operacional. Por exemplo, em sistemas operacionais baseados em Unix, o nome após a exclusão do namespace deve ser um nome de arquivo válido.

Atributos

Exceções

name é inválido. Isso pode ser por vários motivos, incluindo algumas restrições impostas pelo sistema operacional, como um prefixo desconhecido ou caracteres inválidos. Observe que o nome e os prefixos comuns "Global\" e "Local\" diferenciam maiúsculas de minúsculas.

- ou -

Ocorreu outro erro. A propriedade HResult pode fornecer mais informações.

Somente Windows: name especificou um namespace desconhecido. Confira mais informações em Nomes do objeto.

O name é muito longo. As restrições de comprimento podem depender do sistema operacional ou da configuração.

O evento nomeado existe e tem segurança de controle de acesso, mas o usuário não tem FullControl.

Não é possível criar um objeto de sincronização com o name fornecido. Um objeto de sincronização de um tipo diferente pode ter o mesmo nome.

O valor de enumeração mode estava fora do intervalo legal.

- ou -

Somente .NET Framework: name é maior que MAX_PATH (260 caracteres).

Comentários

O name pode ser prefixado com Global\ ou Local\ para especificar um namespace. Quando o Global namespace é especificado, o objeto de sincronização pode ser compartilhado com todos os processos no sistema. Quando o Local namespace é especificado, que também é o padrão quando nenhum namespace é especificado, o objeto de sincronização pode ser compartilhado com processos na mesma sessão. No Windows, uma sessão é uma sessão de logon e os serviços normalmente são executados em uma sessão não interativa diferente. Em sistemas operacionais semelhantes ao Unix, cada shell tem sua própria sessão. Objetos de sincronização local de sessão podem ser apropriados para sincronização entre processos com uma relação pai/filho em que todos eles são executados na mesma sessão. Para obter mais informações sobre nomes de objetos de sincronização no Windows, consulte Nomes de objeto.

Se um name for fornecido e um objeto de sincronização do tipo solicitado já existir no namespace , o objeto de sincronização existente será aberto. Se um objeto de sincronização de um tipo diferente já existir no namespace , um WaitHandleCannotBeOpenedException será gerado. Caso contrário, um novo objeto de sincronização será criado.

Se um evento do sistema com o nome especificado para o name parâmetro já existir, o initialState parâmetro será ignorado.

Cuidado

Por padrão, um evento nomeado não é restrito ao usuário que o criou. Outros usuários podem ser capazes de abrir e usar o evento, incluindo interferir no evento definindo-o ou redefinindo-o inadequadamente. Para restringir o acesso a usuários específicos, você pode usar uma sobrecarga de construtor ou EventWaitHandleAcl e passar um EventWaitHandleSecurity ao criar o evento nomeado. Evite usar eventos nomeados sem restrições de acesso em sistemas que podem ter usuários não confiáveis executando código.

Importante

Ao usar esse construtor para eventos de sistema nomeados, especifique false para initialState. Esse construtor não fornece nenhuma maneira de determinar se um evento de sistema nomeado foi criado, portanto, você não pode fazer nenhuma suposição sobre o estado do evento nomeado. Para determinar se um evento nomeado foi criado, use o EventWaitHandle(Boolean, EventResetMode, String, Boolean) construtor ou o EventWaitHandle(Boolean, EventResetMode, String, Boolean, EventWaitHandleSecurity) construtor .

Se o estado inicial do evento não for atribuído, os threads que aguardarem o evento serão bloqueados. Se o estado inicial for sinalizado e o ManualReset sinalizador for especificado para mode, os threads que aguardarem o evento não serão bloqueados. Se o estado inicial for sinalizado e mode for AutoReset, o primeiro thread que aguardar o evento será liberado imediatamente, após o qual o evento será redefinido e os threads subsequentes serão bloqueados.

Confira também

Aplica-se a

EventWaitHandle(Boolean, EventResetMode, String, Boolean)

Origem:
EventWaitHandle.cs
Origem:
EventWaitHandle.cs
Origem:
EventWaitHandle.cs

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.

public:
 EventWaitHandle(bool initialState, System::Threading::EventResetMode mode, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew);
[System.Security.SecurityCritical]
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name, out bool createdNew);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string? name, out bool createdNew);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name, out bool createdNew);
[<System.Security.SecurityCritical>]
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string * bool -> System.Threading.EventWaitHandle
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string * bool -> System.Threading.EventWaitHandle
Public Sub New (initialState As Boolean, mode As EventResetMode, name As String, ByRef createdNew As Boolean)

Parâmetros

initialState
Boolean

true para definir o estado inicial como sinalizado se o evento nomeado for criado como resultado dessa chamada, false para defini-lo como não sinalizado.

mode
EventResetMode

Um dos valores EventResetMode que determina se o evento redefine automática ou manualmente.

name
String

O nome, se o objeto de sincronização deve ser compartilhado com outros processos; caso contrário, null ou uma cadeia de caracteres vazia. O nome diferencia maiúsculas de minúsculas. O caractere de barra invertida (\) é reservado e só pode ser usado para especificar um namespace. Para obter mais informações sobre namespaces, consulte a seção comentários. Pode haver mais restrições sobre o nome, dependendo do sistema operacional. Por exemplo, em sistemas operacionais baseados em Unix, o nome após a exclusão do namespace deve ser um nome de arquivo válido.

createdNew
Boolean

Quando esse método for retornado, conterá true se um evento local tiver sido criado (ou seja, se name for null ou uma cadeia de caracteres vazia) ou se o evento de sistema nomeado especificado tiver sido criado; false se o evento de sistema nomeado especificado já existia. Este parâmetro é passado não inicializado.

Atributos

Exceções

name é inválido. Isso pode ser por vários motivos, incluindo algumas restrições impostas pelo sistema operacional, como um prefixo desconhecido ou caracteres inválidos. Observe que o nome e os prefixos comuns "Global\" e "Local\" diferenciam maiúsculas de minúsculas.

- ou -

Ocorreu outro erro. A propriedade HResult pode fornecer mais informações.

Somente Windows: name especificou um namespace desconhecido. Confira mais informações em Nomes do objeto.

O name é muito longo. As restrições de comprimento podem depender do sistema operacional ou da configuração.

O evento nomeado existe e tem segurança de controle de acesso, mas o usuário não tem FullControl.

Não é possível criar um objeto de sincronização com o name fornecido. Um objeto de sincronização de um tipo diferente pode ter o mesmo nome.

O valor de enumeração mode estava fora do intervalo legal.

- ou -

Somente .NET Framework: name é maior que MAX_PATH (260 caracteres).

Comentários

O name pode ser prefixado com Global\ ou Local\ para especificar um namespace. Quando o Global namespace é especificado, o objeto de sincronização pode ser compartilhado com todos os processos no sistema. Quando o Local namespace é especificado, que também é o padrão quando nenhum namespace é especificado, o objeto de sincronização pode ser compartilhado com processos na mesma sessão. No Windows, uma sessão é uma sessão de logon e os serviços normalmente são executados em uma sessão não interativa diferente. Em sistemas operacionais semelhantes ao Unix, cada shell tem sua própria sessão. Objetos de sincronização local de sessão podem ser apropriados para sincronização entre processos com uma relação pai/filho em que todos eles são executados na mesma sessão. Para obter mais informações sobre nomes de objetos de sincronização no Windows, consulte Nomes de objeto.

Se um name for fornecido e um objeto de sincronização do tipo solicitado já existir no namespace , o objeto de sincronização existente será aberto. Se um objeto de sincronização de um tipo diferente já existir no namespace , um WaitHandleCannotBeOpenedException será gerado. Caso contrário, um novo objeto de sincronização será criado.

Se um evento do sistema com o nome especificado para o name parâmetro já existir, o initialState parâmetro será ignorado. Depois de chamar esse construtor, use o valor na variável especificada para o ref parâmetro (ByRef parâmetro no Visual Basic)createdNew para determinar se o evento do sistema nomeado já existia ou foi criado.

Se o estado inicial do evento não for atribuído, os threads que aguardarem o evento serão bloqueados. Se o estado inicial for sinalizado e o ManualReset sinalizador for especificado para mode, os threads que aguardarem o evento não serão bloqueados. Se o estado inicial for sinalizado e mode for AutoReset, o primeiro thread que aguardar o evento será liberado imediatamente, após o qual o evento será redefinido e os threads subsequentes serão bloqueados.

Cuidado

Por padrão, um evento nomeado não é restrito ao usuário que o criou. Outros usuários podem ser capazes de abrir e usar o evento, incluindo interferir no evento definindo-o ou redefinindo-o inadequadamente. Para restringir o acesso a usuários específicos, você pode usar uma sobrecarga de construtor ou EventWaitHandleAcl e passar um EventWaitHandleSecurity ao criar o evento nomeado. Evite usar eventos nomeados sem restrições de acesso em sistemas que podem ter usuários não confiáveis executando código.

Confira também

Aplica-se a

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.

public:
 EventWaitHandle(bool initialState, System::Threading::EventResetMode mode, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew, System::Security::AccessControl::EventWaitHandleSecurity ^ eventSecurity);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name, out bool createdNew, System.Security.AccessControl.EventWaitHandleSecurity eventSecurity);
[System.Security.SecurityCritical]
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name, out bool createdNew, System.Security.AccessControl.EventWaitHandleSecurity eventSecurity);
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string * bool * System.Security.AccessControl.EventWaitHandleSecurity -> System.Threading.EventWaitHandle
[<System.Security.SecurityCritical>]
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string * bool * System.Security.AccessControl.EventWaitHandleSecurity -> System.Threading.EventWaitHandle
Public Sub New (initialState As Boolean, mode As EventResetMode, name As String, ByRef createdNew As Boolean, eventSecurity As EventWaitHandleSecurity)

Parâmetros

initialState
Boolean

true para definir o estado inicial como sinalizado se o evento nomeado for criado como resultado dessa chamada, false para defini-lo como não sinalizado.

mode
EventResetMode

Um dos valores EventResetMode que determina se o evento redefine automática ou manualmente.

name
String

O nome, se o objeto de sincronização deve ser compartilhado com outros processos; caso contrário, null ou uma cadeia de caracteres vazia. O nome diferencia maiúsculas de minúsculas. O caractere de barra invertida (\) é reservado e só pode ser usado para especificar um namespace. Para obter mais informações sobre namespaces, consulte a seção comentários. Pode haver mais restrições sobre o nome, dependendo do sistema operacional. Por exemplo, em sistemas operacionais baseados em Unix, o nome após a exclusão do namespace deve ser um nome de arquivo válido.

createdNew
Boolean

Quando esse método for retornado, conterá true se um evento local tiver sido criado (ou seja, se name for null ou uma cadeia de caracteres vazia) ou se o evento de sistema nomeado especificado tiver sido criado; false se o evento de sistema nomeado especificado já existia. Este parâmetro é passado não inicializado.

eventSecurity
EventWaitHandleSecurity

Um objeto EventWaitHandleSecurity que representa a segurança de controle de acesso a ser aplicada ao evento de sistema nomeado.

Atributos

Exceções

name é inválido. Isso pode ser por vários motivos, incluindo algumas restrições impostas pelo sistema operacional, como um prefixo desconhecido ou caracteres inválidos. Observe que o nome e os prefixos comuns "Global\" e "Local\" diferenciam maiúsculas de minúsculas.

- ou -

Ocorreu outro erro. A propriedade HResult pode fornecer mais informações.

Somente Windows: name especificou um namespace desconhecido. Confira mais informações em Nomes do objeto.

O name é muito longo. As restrições de comprimento podem depender do sistema operacional ou da configuração.

O evento nomeado existe e tem segurança de controle de acesso, mas o usuário não tem FullControl.

Não é possível criar um objeto de sincronização com o name fornecido. Um objeto de sincronização de um tipo diferente pode ter o mesmo nome.

O valor de enumeração mode estava fora do intervalo legal.

- ou -

Somente .NET Framework: name é maior que MAX_PATH (260 caracteres).

Exemplos

O exemplo de código a seguir demonstra o comportamento entre processos de um evento de sistema nomeado com segurança de controle de acesso. O exemplo usa a sobrecarga do OpenExisting(String) método para testar a existência de um evento nomeado.

Se o evento não existir, ele será criado com propriedade inicial e segurança de controle de acesso que nega ao usuário atual o direito de usar o evento, mas concede o direito de ler e alterar permissões no evento.

Se você executar o exemplo compilado em duas janelas de comando, a segunda cópia gerará uma exceção de violação de acesso na chamada para OpenExisting(String). A exceção é capturada e o exemplo usa a sobrecarga do OpenExisting(String, EventWaitHandleRights) método para aguardar o evento com os direitos necessários para ler e alterar as permissões.

Depois que as permissões são alteradas, o evento é aberto com os direitos necessários para aguardá-lo e sinalizá-lo. Se você executar o exemplo compilado de uma terceira janela de comando, o exemplo será executado usando as novas permissões.

using namespace System;
using namespace System::Threading;
using namespace System::Security::AccessControl;
using namespace System::Security::Permissions;

public ref class Example
{
public:
   [SecurityPermissionAttribute(SecurityAction::Demand,Flags=SecurityPermissionFlag::UnmanagedCode)]
   static void Main()
   {
      String^ ewhName = L"EventWaitHandleExample5";

      EventWaitHandle^ ewh = nullptr;
      bool doesNotExist = false;
      bool unauthorized = false;
      
      // The value of this variable is set by the event
      // constructor. It is true if the named system event was
      // created, and false if the named event already existed.
      //
      bool wasCreated;
      
      // Attempt to open the named event.
      try
      {
         // Open the event with (EventWaitHandleRights.Synchronize
         // | EventWaitHandleRights.Modify), to wait on and
         // signal the named event.
         //
         ewh = EventWaitHandle::OpenExisting( ewhName );
      }
      catch ( WaitHandleCannotBeOpenedException^ ) 
      {
         Console::WriteLine( L"Named event does not exist." );
         doesNotExist = true;
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message );
         unauthorized = true;
      }

      // There are three cases: (1) The event does not exist.
      // (2) The event exists, but the current user doesn't
      // have access. (3) The event exists and the user has
      // access.
      //
      if ( doesNotExist )
      {
         // The event does not exist, so create it.

         // Create an access control list (ACL) that denies the
         // current user the right to wait on or signal the
         // event, but allows the right to read and change
         // security information for the event.
         //
         String^ user = String::Concat( Environment::UserDomainName, L"\\",
            Environment::UserName );
         EventWaitHandleSecurity^ ewhSec = gcnew EventWaitHandleSecurity;
         //following constructor fails
         EventWaitHandleAccessRule^ rule = gcnew EventWaitHandleAccessRule(
            user,
            static_cast<EventWaitHandleRights>(
               EventWaitHandleRights::Synchronize | 
               EventWaitHandleRights::Modify),
            AccessControlType::Deny );
         ewhSec->AddAccessRule( rule );

         rule = gcnew EventWaitHandleAccessRule( user,
            static_cast<EventWaitHandleRights>(
               EventWaitHandleRights::ReadPermissions | 
               EventWaitHandleRights::ChangePermissions),
            AccessControlType::Allow );
         ewhSec->AddAccessRule( rule );
         
         // Create an EventWaitHandle object that represents
         // the system event named by the constant 'ewhName',
         // initially signaled, with automatic reset, and with
         // the specified security access. The Boolean value that
         // indicates creation of the underlying system object
         // is placed in wasCreated.
         //
         ewh = gcnew EventWaitHandle( true,
            EventResetMode::AutoReset,
            ewhName,
            wasCreated,
            ewhSec );
         
         // If the named system event was created, it can be
         // used by the current instance of this program, even
         // though the current user is denied access. The current
         // program owns the event. Otherwise, exit the program.
         //
         if ( wasCreated )
         {
            Console::WriteLine( L"Created the named event." );
         }
         else
         {
            Console::WriteLine( L"Unable to create the event." );
            return;
         }
      }
      else if ( unauthorized )
      {
         // Open the event to read and change the access control
         // security. The access control security defined above
         // allows the current user to do this.
         //
         try
         {
            ewh = EventWaitHandle::OpenExisting( ewhName, 
               static_cast<EventWaitHandleRights>(
                  EventWaitHandleRights::ReadPermissions |
                  EventWaitHandleRights::ChangePermissions) );
            
            // Get the current ACL. This requires
            // EventWaitHandleRights.ReadPermissions.
            EventWaitHandleSecurity^ ewhSec = ewh->GetAccessControl();
            String^ user = String::Concat( Environment::UserDomainName, L"\\",
               Environment::UserName );
            
            // First, the rule that denied the current user
            // the right to enter and release the event must
            // be removed.
            EventWaitHandleAccessRule^ rule = gcnew EventWaitHandleAccessRule(
               user,
               static_cast<EventWaitHandleRights>(
                  EventWaitHandleRights::Synchronize |
                  EventWaitHandleRights::Modify),
               AccessControlType::Deny );
            ewhSec->RemoveAccessRule( rule );
            
            // Now grant the user the correct rights.
            //
            rule = gcnew EventWaitHandleAccessRule( user,
               static_cast<EventWaitHandleRights>(
                  EventWaitHandleRights::Synchronize |
                  EventWaitHandleRights::Modify),
               AccessControlType::Allow );
            ewhSec->AddAccessRule( rule );
            
            // Update the ACL. This requires
            // EventWaitHandleRights.ChangePermissions.
            ewh->SetAccessControl( ewhSec );
            Console::WriteLine( L"Updated event security." );
            
            // Open the event with (EventWaitHandleRights.Synchronize
            // | EventWaitHandleRights.Modify), the rights required
            // to wait on and signal the event.
            //
            ewh = EventWaitHandle::OpenExisting( ewhName );
         }
         catch ( UnauthorizedAccessException^ ex ) 
         {
            Console::WriteLine( L"Unable to change permissions: {0}",
               ex->Message );
            return;
         }

      }
      
      // Wait on the event, and hold it until the program
      // exits.
      //
      try
      {
         Console::WriteLine( L"Wait on the event." );
         ewh->WaitOne();
         Console::WriteLine( L"Event was signaled." );
         Console::WriteLine( L"Press the Enter key to signal the event and exit." );
         Console::ReadLine();
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message );
      }
      finally
      {
         ewh->Set();
      }
   }
};

int main()
{
   Example::Main();
}
using System;
using System.Threading;
using System.Security.AccessControl;

internal class Example
{
    internal static void Main()
    {
        const string ewhName = "EventWaitHandleExample5";

        EventWaitHandle ewh = null;
        bool doesNotExist = false;
        bool unauthorized = false;

        // The value of this variable is set by the event
        // constructor. It is true if the named system event was
        // created, and false if the named event already existed.
        //
        bool wasCreated;

        // Attempt to open the named event.
        try
        {
            // Open the event with (EventWaitHandleRights.Synchronize
            // | EventWaitHandleRights.Modify), to wait on and 
            // signal the named event.
            //
            ewh = EventWaitHandle.OpenExisting(ewhName);
        }
        catch (WaitHandleCannotBeOpenedException)
        {
            Console.WriteLine("Named event does not exist.");
            doesNotExist = true;
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
            unauthorized = true;
        }

        // There are three cases: (1) The event does not exist.
        // (2) The event exists, but the current user doesn't 
        // have access. (3) The event exists and the user has
        // access.
        //
        if (doesNotExist)
        {
            // The event does not exist, so create it.

            // Create an access control list (ACL) that denies the
            // current user the right to wait on or signal the 
            // event, but allows the right to read and change
            // security information for the event.
            //
            string user = Environment.UserDomainName + "\\"
                + Environment.UserName;
            EventWaitHandleSecurity ewhSec = 
                new EventWaitHandleSecurity();

            EventWaitHandleAccessRule rule = 
                new EventWaitHandleAccessRule(user, 
                    EventWaitHandleRights.Synchronize | 
                    EventWaitHandleRights.Modify, 
                    AccessControlType.Deny);
            ewhSec.AddAccessRule(rule);

            rule = new EventWaitHandleAccessRule(user, 
                EventWaitHandleRights.ReadPermissions | 
                EventWaitHandleRights.ChangePermissions, 
                AccessControlType.Allow);
            ewhSec.AddAccessRule(rule);

            // Create an EventWaitHandle object that represents
            // the system event named by the constant 'ewhName', 
            // initially signaled, with automatic reset, and with
            // the specified security access. The Boolean value that 
            // indicates creation of the underlying system object
            // is placed in wasCreated.
            //
            ewh = new EventWaitHandle(true, 
                EventResetMode.AutoReset, 
                ewhName, 
                out wasCreated, 
                ewhSec);

            // If the named system event was created, it can be
            // used by the current instance of this program, even 
            // though the current user is denied access. The current
            // program owns the event. Otherwise, exit the program.
            // 
            if (wasCreated)
            {
                Console.WriteLine("Created the named event.");
            }
            else
            {
                Console.WriteLine("Unable to create the event.");
                return;
            }
        }
        else if (unauthorized)
        {
            // Open the event to read and change the access control
            // security. The access control security defined above
            // allows the current user to do this.
            //
            try
            {
                ewh = EventWaitHandle.OpenExisting(ewhName, 
                    EventWaitHandleRights.ReadPermissions | 
                    EventWaitHandleRights.ChangePermissions);

                // Get the current ACL. This requires 
                // EventWaitHandleRights.ReadPermissions.
                EventWaitHandleSecurity ewhSec = ewh.GetAccessControl();
                
                string user = Environment.UserDomainName + "\\"
                    + Environment.UserName;

                // First, the rule that denied the current user 
                // the right to enter and release the event must
                // be removed.
                EventWaitHandleAccessRule rule = 
                    new EventWaitHandleAccessRule(user, 
                        EventWaitHandleRights.Synchronize | 
                        EventWaitHandleRights.Modify, 
                        AccessControlType.Deny);
                ewhSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new EventWaitHandleAccessRule(user, 
                    EventWaitHandleRights.Synchronize | 
                    EventWaitHandleRights.Modify, 
                    AccessControlType.Allow);
                ewhSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // EventWaitHandleRights.ChangePermissions.
                ewh.SetAccessControl(ewhSec);

                Console.WriteLine("Updated event security.");

                // Open the event with (EventWaitHandleRights.Synchronize 
                // | EventWaitHandleRights.Modify), the rights required
                // to wait on and signal the event.
                //
                ewh = EventWaitHandle.OpenExisting(ewhName);
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}",
                    ex.Message);
                return;
            }
        }

        // Wait on the event, and hold it until the program
        // exits.
        //
        try
        {
            Console.WriteLine("Wait on the event.");
            ewh.WaitOne();
            Console.WriteLine("Event was signaled.");
            Console.WriteLine("Press the Enter key to signal the event and exit.");
            Console.ReadLine();
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
        }
        finally
        {
            ewh.Set();
        }
    }
}
Imports System.Threading
Imports System.Security.AccessControl

Friend Class Example

    <MTAThread> _
    Friend Shared Sub Main()
        Const ewhName As String = "EventWaitHandleExample5"

        Dim ewh As EventWaitHandle = Nothing
        Dim doesNotExist as Boolean = False
        Dim unauthorized As Boolean = False

        ' The value of this variable is set by the event
        ' constructor. It is True if the named system event was
        ' created, and False if the named event already existed.
        '
        Dim wasCreated As Boolean

        ' Attempt to open the named event.
        Try
            ' Open the event with (EventWaitHandleRights.Synchronize
            ' Or EventWaitHandleRights.Modify), to wait on and 
            ' signal the named event.
            '
            ewh = EventWaitHandle.OpenExisting(ewhName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Named event does not exist.")
            doesNotExist = True
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", ex.Message)
            unauthorized = True
        End Try

        ' There are three cases: (1) The event does not exist.
        ' (2) The event exists, but the current user doesn't 
        ' have access. (3) The event exists and the user has
        ' access.
        '
        If doesNotExist Then
            ' The event does not exist, so create it.

            ' Create an access control list (ACL) that denies the
            ' current user the right to wait on or signal the 
            ' event, but allows the right to read and change
            ' security information for the event.
            '
            Dim user As String = Environment.UserDomainName _ 
                & "\" & Environment.UserName
            Dim ewhSec As New EventWaitHandleSecurity()

            Dim rule As New EventWaitHandleAccessRule(user, _
                EventWaitHandleRights.Synchronize Or _
                EventWaitHandleRights.Modify, _
                AccessControlType.Deny)
            ewhSec.AddAccessRule(rule)

            rule = New EventWaitHandleAccessRule(user, _
                EventWaitHandleRights.ReadPermissions Or _
                EventWaitHandleRights.ChangePermissions, _
                AccessControlType.Allow)
            ewhSec.AddAccessRule(rule)

            ' Create an EventWaitHandle object that represents
            ' the system event named by the constant 'ewhName', 
            ' initially signaled, with automatic reset, and with
            ' the specified security access. The Boolean value that 
            ' indicates creation of the underlying system object
            ' is placed in wasCreated.
            '
            ewh = New EventWaitHandle(True, _
                EventResetMode.AutoReset, ewhName, _
                wasCreated, ewhSec)

            ' If the named system event was created, it can be
            ' used by the current instance of this program, even 
            ' though the current user is denied access. The current
            ' program owns the event. Otherwise, exit the program.
            ' 
            If wasCreated Then
                Console.WriteLine("Created the named event.")
            Else
                Console.WriteLine("Unable to create the event.")
                Return
            End If

        ElseIf unauthorized Then

            ' Open the event to read and change the access control
            ' security. The access control security defined above
            ' allows the current user to do this.
            '
            Try
                ewh = EventWaitHandle.OpenExisting(ewhName, _
                    EventWaitHandleRights.ReadPermissions Or _
                    EventWaitHandleRights.ChangePermissions)

                ' Get the current ACL. This requires 
                ' EventWaitHandleRights.ReadPermissions.
                Dim ewhSec As EventWaitHandleSecurity = _
                    ewh.GetAccessControl()
                
                Dim user As String = Environment.UserDomainName _ 
                    & "\" & Environment.UserName

                ' First, the rule that denied the current user 
                ' the right to enter and release the event must
                ' be removed.
                Dim rule As New EventWaitHandleAccessRule(user, _
                    EventWaitHandleRights.Synchronize Or _
                    EventWaitHandleRights.Modify, _
                    AccessControlType.Deny)
                ewhSec.RemoveAccessRule(rule)

                ' Now grant the user the correct rights.
                ' 
                rule = New EventWaitHandleAccessRule(user, _
                    EventWaitHandleRights.Synchronize Or _
                    EventWaitHandleRights.Modify, _
                    AccessControlType.Allow)
                ewhSec.AddAccessRule(rule)

                ' Update the ACL. This requires
                ' EventWaitHandleRights.ChangePermissions.
                ewh.SetAccessControl(ewhSec)

                Console.WriteLine("Updated event security.")

                ' Open the event with (EventWaitHandleRights.Synchronize 
                ' Or EventWaitHandleRights.Modify), the rights required
                ' to wait on and signal the event.
                '
                ewh = EventWaitHandle.OpenExisting(ewhName)

            Catch ex As UnauthorizedAccessException
                Console.WriteLine("Unable to change permissions: {0}", _
                    ex.Message)
                Return
            End Try

        End If

        ' Wait on the event, and hold it until the program
        ' exits.
        '
        Try
            Console.WriteLine("Wait on the event.")
            ewh.WaitOne()
            Console.WriteLine("Event was signaled.")
            Console.WriteLine("Press the Enter key to signal the event and exit.")
            Console.ReadLine()
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", _
                ex.Message)
        Finally
            ewh.Set()
        End Try
    End Sub 
End Class

Comentários

Use esse construtor para aplicar a segurança de controle de acesso a um evento de sistema nomeado quando ele for criado, impedindo que outro código assumisse o controle do evento.

Esse construtor inicializa um EventWaitHandle objeto que representa um evento do sistema. Você pode criar vários EventWaitHandle objetos que representam o mesmo evento do sistema.

Se o evento do sistema não existir, ele será criado com a segurança de controle de acesso especificada. Se o evento existir, a segurança de controle de acesso especificada será ignorada.

Observação

O chamador tem controle total sobre o objeto recém-criado EventWaitHandle , mesmo que eventSecurity negue ou não conceda alguns direitos de acesso ao usuário atual. No entanto, se o usuário atual tentar obter outro EventWaitHandle objeto para representar o mesmo evento nomeado, usando um construtor ou o método , a segurança do controle de acesso do OpenExisting Windows será aplicada.

O name pode ser prefixado com Global\ ou Local\ para especificar um namespace. Quando o Global namespace é especificado, o objeto de sincronização pode ser compartilhado com todos os processos no sistema. Quando o Local namespace é especificado, que também é o padrão quando nenhum namespace é especificado, o objeto de sincronização pode ser compartilhado com processos na mesma sessão. No Windows, uma sessão é uma sessão de logon e os serviços normalmente são executados em uma sessão não interativa diferente. Em sistemas operacionais semelhantes ao Unix, cada shell tem sua própria sessão. Objetos de sincronização local de sessão podem ser apropriados para sincronização entre processos com uma relação pai/filho em que todos eles são executados na mesma sessão. Para obter mais informações sobre nomes de objetos de sincronização no Windows, consulte Nomes de objeto.

Se um name for fornecido e um objeto de sincronização do tipo solicitado já existir no namespace , o objeto de sincronização existente será aberto. Se um objeto de sincronização de um tipo diferente já existir no namespace , um WaitHandleCannotBeOpenedException será gerado. Caso contrário, um novo objeto de sincronização será criado.

Se um evento do sistema com o nome especificado para o name parâmetro já existir, o initialState parâmetro será ignorado. Depois de chamar esse construtor, use o valor na variável especificada para o ref parâmetro (ByRef parâmetro no Visual Basic) createdNew para determinar se o evento do sistema nomeado já existia ou foi criado.

Se o estado inicial do evento não for atribuído, os threads que aguardarem o evento serão bloqueados. Se o estado inicial for sinalizado e o ManualReset sinalizador for especificado para mode, os threads que aguardarem o evento não serão bloqueados. Se o estado inicial for sinalizado e mode for AutoReset, o primeiro thread que aguardar o evento será liberado imediatamente, após o qual o evento será redefinido e os threads subsequentes serão bloqueados.

Cuidado

Por padrão, um evento nomeado não é restrito ao usuário que o criou. Outros usuários podem ser capazes de abrir e usar o evento, incluindo interferir no evento definindo-o ou redefinindo-o inadequadamente. Para restringir o acesso a usuários específicos, você pode passar um EventWaitHandleSecurity ao criar o evento nomeado. Evite usar eventos nomeados sem restrições de acesso em sistemas que podem ter usuários não confiáveis executando código.

Confira também

Aplica-se a