EventWaitHandle.OpenExisting Método

Definição

Abre um evento de sincronização nomeado especificado, se ele já existir.Opens a specified named synchronization event, if it already exists.

Sobrecargas

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.

OpenExisting(String)

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

public:
 static System::Threading::EventWaitHandle ^ OpenExisting(System::String ^ name);
public static System.Threading.EventWaitHandle OpenExisting (string name);
[System.Security.SecurityCritical]
public static System.Threading.EventWaitHandle OpenExisting (string name);
static member OpenExisting : string -> System.Threading.EventWaitHandle
[<System.Security.SecurityCritical>]
static member OpenExisting : string -> System.Threading.EventWaitHandle
Public Shared Function OpenExisting (name As String) As EventWaitHandle

Parâmetros

name
String

O nome do objeto de sincronização a ser aberto e compartilhado com outros processos.The name of the synchronization object to be opened and shared with other processes. O nome diferencia maiúsculas de minúsculas.The name is case-sensitive.

Retornos

EventWaitHandle

Um objeto que representa o evento do sistema nomeado.An object that represents the named system event.

Atributos

Exceções

Não é possível abrir um objeto de sincronização com o name fornecido.A synchronization object with the provided name cannot be opened. Pode não existir ou um objeto de sincronização de um tipo diferente pode ter o mesmo nome.It may not exist, or a synchronization object of a different type might have the same name. Em alguns casos, essa exceção pode ser lançada para nomes inválidos.In some cases, this exception may be thrown for invalid names.

name é uma cadeia de caracteres vazia.name is an empty string.

- ou --or-

Somente .NET Framework: name é maior que MAX_PATH (260 caracteres)..NET Framework only: name is longer than MAX_PATH (260 characters).

name é null.name is null.

name é inválido.name is invalid. Isso pode ser por vários motivos, incluindo algumas restrições impostas pelo sistema operacional, como um prefixo desconhecido ou caracteres inválidos.This can be for various reasons, including some restrictions that may be placed by the operating system, such as an unknown prefix or invalid characters. Observe que o nome e os prefixos comuns "Global" e "Local" diferenciam maiúsculas de minúsculas.Note that the name and common prefixes "Global" and "Local" are case-sensitive.

- ou --or-

Ocorreu outro erro.There was some other error. A propriedade HResult pode fornecer mais informações.The HResult property may provide more information.

Somente Windows: name especificou um namespace desconhecido.Windows only: name specified an unknown namespace. Confira mais informações em Nomes do objeto.See Object Names for more information.

O name é muito longo.The name is too long. As restrições de comprimento podem depender do sistema operacional ou da configuração.Length restrictions may depend on the operating system or configuration.

O evento nomeado existe, mas o usuário não tem o acesso de segurança necessário para usá-lo.The named event exists, but the user does not have the security access required to use it.

Exemplos

O exemplo de código a seguir demonstra o comportamento de processo cruzado de um evento do sistema nomeado com segurança de controle de acesso.The following code example demonstrates the cross-process behavior of a named system event with access control security. O exemplo usa a OpenExisting(String) sobrecarga do método para testar a existência de um evento nomeado.The example uses the OpenExisting(String) method overload to test for the existence of a named event.

Se o evento não existir, ele será criado com a propriedade inicial e a 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.If the event does not exist, it is created with initial ownership and access control security that denies the current user the right to use the event, but grants the right to read and change permissions on the event.

Se você executar o exemplo compilado de duas janelas de comando, a segunda cópia gerará uma exceção de violação de acesso na chamada para OpenExisting(String) .If you run the compiled example from two command windows, the second copy will throw an access violation exception on the call to OpenExisting(String). A exceção é capturada e o exemplo usa a OpenExisting(String, EventWaitHandleRights) sobrecarga do método para aguardar o evento com os direitos necessários para ler e alterar as permissões.The exception is caught, and the example uses the OpenExisting(String, EventWaitHandleRights) method overload to wait on the event with the rights needed to read and change the permissions.

Depois que as permissões forem alteradas, o evento será aberto com os direitos necessários para aguardar e signalá-lo.After the permissions are changed, the event is opened with the rights required to wait on it and signal it. Se você executar o exemplo compilado de uma terceira janela de comando, o exemplo será executado usando as novas permissões.If you run the compiled example from a third command window, the example runs using the new permissions.

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

O name pode ser prefixado com Global\ or Local\ para especificar um namespace.The name may be prefixed with Global\ or Local\ to specify a namespace. Quando o Global namespace é especificado, o objeto de sincronização pode ser compartilhado com qualquer processo no sistema.When the Global namespace is specified, the synchronization object may be shared with any processes on the system. 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.When the Local namespace is specified, which is also the default when no namespace is specified, the synchronization object may be shared with processes in the same session. 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.On Windows, a session is a login session, and services typically run in a different non-interactive session. Em sistemas operacionais semelhantes ao Unix, cada shell tem sua própria sessão.On Unix-like operating systems, each shell has its own session. Os objetos de sincronização de sessão local podem ser apropriados para sincronizar entre processos com uma relação pai/filho em que todos eles são executados na mesma sessão.Session-local synchronization objects may be appropriate for synchronizing between processes with a parent/child relationship where they all run in the same session. Para obter mais informações sobre nomes de objetos Synchornization no Windows, consulte nomes de objetos.For more information about synchornization object names on Windows, see Object Names.

Se um objeto de sincronização do tipo solicitado existir no namespace, o objeto de sincronização existente será aberto.If a synchronization object of the requested type exists in the namespace, the existing synchronization object is opened. Se um objeto de sincronização não existir no namespace ou se um objeto de sincronização de um tipo diferente existir no namespace, um WaitHandleCannotBeOpenedException será gerado.If a synchronization object does not exist in the namespace, or a synchronization object of a different type exists in the namespace, a WaitHandleCannotBeOpenedException is thrown.

O OpenExisting método tenta abrir o evento de sistema nomeado especificado.The OpenExisting method tries to open the specified named system event. Para criar o evento do sistema quando ele ainda não existir, use um dos EventWaitHandle construtores que tem um name parâmetro.To create the system event when it does not already exist, use one of the EventWaitHandle constructors that has a name parameter.

Várias chamadas para esse método que usam o mesmo valor para não name retornam necessariamente o mesmo EventWaitHandle objeto, embora os objetos retornados representem o mesmo evento de sistema nomeado.Multiple calls to this method that use the same value for name do not necessarily return the same EventWaitHandle object, even though the objects that are returned represent the same named system event.

Essa sobrecarga de método é equivalente à chamada da OpenExisting(String, EventWaitHandleRights) sobrecarga do método e à especificação EventWaitHandleRights.Synchronize e EventWaitHandleRights.Modify aos direitos, combinados com o uso da operação OR bit a bit.This method overload is equivalent to calling the OpenExisting(String, EventWaitHandleRights) method overload and specifying EventWaitHandleRights.Synchronize and EventWaitHandleRights.Modify rights, combined by using the bitwise OR operation.

A especificação do EventWaitHandleRights.Synchronize sinalizador permite que um thread aguarde o evento do sistema nomeado e especificar o EventWaitHandleRights.Modify sinalizador permite que um thread chame os Set Reset métodos e.Specifying the EventWaitHandleRights.Synchronize flag allows a thread to wait on the named system event, and specifying the EventWaitHandleRights.Modify flag allows a thread to call the Set and Reset methods.

Veja também

Aplica-se a

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.

public:
 static System::Threading::EventWaitHandle ^ OpenExisting(System::String ^ name, System::Security::AccessControl::EventWaitHandleRights rights);
public static System.Threading.EventWaitHandle OpenExisting (string name, System.Security.AccessControl.EventWaitHandleRights rights);
[System.Security.SecurityCritical]
public static System.Threading.EventWaitHandle OpenExisting (string name, System.Security.AccessControl.EventWaitHandleRights rights);
static member OpenExisting : string * System.Security.AccessControl.EventWaitHandleRights -> System.Threading.EventWaitHandle
[<System.Security.SecurityCritical>]
static member OpenExisting : string * System.Security.AccessControl.EventWaitHandleRights -> System.Threading.EventWaitHandle
Public Shared Function OpenExisting (name As String, rights As EventWaitHandleRights) As EventWaitHandle

Parâmetros

name
String

O nome do objeto de sincronização a ser aberto e compartilhado com outros processos.The name of the synchronization object to be opened and shared with other processes. O nome diferencia maiúsculas de minúsculas.The name is case-sensitive.

rights
EventWaitHandleRights

Uma combinação bit a bit dos valores de enumeração que representa o acesso de segurança desejado.A bitwise combination of the enumeration values that represent the desired security access.

Retornos

EventWaitHandle

Um objeto que representa o evento do sistema nomeado.An object that represents the named system event.

Atributos

Exceções

name é uma cadeia de caracteres vazia.name is an empty string.

- ou --or-

Somente .NET Framework: name é maior que MAX_PATH (260 caracteres)..NET Framework only: name is longer than MAX_PATH (260 characters).

name é null.name is null.

Não é possível abrir um objeto de sincronização com o name fornecido.A synchronization object with the provided name cannot be opened. Pode não existir ou um objeto de sincronização de um tipo diferente pode ter o mesmo nome.It may not exist, or a synchronization object of a different type might have the same name. Em alguns casos, essa exceção pode ser lançada para nomes inválidos.In some cases, this exception may be thrown for invalid names.

name é inválido.name is invalid. Isso pode ser por vários motivos, incluindo algumas restrições impostas pelo sistema operacional, como um prefixo desconhecido ou caracteres inválidos.This can be for various reasons, including some restrictions that may be placed by the operating system, such as an unknown prefix or invalid characters. Observe que o nome e os prefixos comuns "Global" e "Local" diferenciam maiúsculas de minúsculas.Note that the name and common prefixes "Global" and "Local" are case-sensitive.

- ou --or-

Ocorreu outro erro.There was some other error. A propriedade HResult pode fornecer mais informações.The HResult property may provide more information.

Somente Windows: name especificou um namespace desconhecido.Windows only: name specified an unknown namespace. Confira mais informações em Nomes do objeto.See Object Names for more information.

O name é muito longo.The name is too long. As restrições de comprimento podem depender do sistema operacional ou da configuração.Length restrictions may depend on the operating system or configuration.

O evento nomeado existe, mas o usuário não tem o acesso de segurança desejado.The named event exists, but the user does not have the desired security access.

Exemplos

O exemplo de código a seguir demonstra o comportamento de processo cruzado de um evento do sistema nomeado com segurança de controle de acesso.The following code example demonstrates the cross-process behavior of a named system event with access control security. O exemplo usa a OpenExisting(String) sobrecarga do método para testar a existência de um evento nomeado.The example uses the OpenExisting(String) method overload to test for the existence of a named event.

Se o evento não existir, ele será criado com a propriedade inicial e a 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.If the event does not exist, it is created with initial ownership and access control security that denies the current user the right to use the event, but grants the right to read and change permissions on the event.

Se você executar o exemplo compilado de duas janelas de comando, a segunda cópia gerará uma exceção de violação de acesso na chamada para OpenExisting(String) .If you run the compiled example from two command windows, the second copy will throw an access violation exception on the call to OpenExisting(String). A exceção é capturada e o exemplo usa a OpenExisting(String, EventWaitHandleRights) sobrecarga do método para aguardar o evento com os direitos necessários para ler e alterar as permissões.The exception is caught, and the example uses the OpenExisting(String, EventWaitHandleRights) method overload to wait on the event with the rights needed to read and change the permissions.

Depois que as permissões forem alteradas, o evento será aberto com os direitos necessários para aguardar e signalá-lo.After the permissions are changed, the event is opened with the rights required to wait on it and signal it. Se você executar o exemplo compilado de uma terceira janela de comando, o exemplo será executado usando as novas permissões.If you run the compiled example from a third command window, the example runs using the new permissions.

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

O name pode ser prefixado com Global\ or Local\ para especificar um namespace.The name may be prefixed with Global\ or Local\ to specify a namespace. Quando o Global namespace é especificado, o objeto de sincronização pode ser compartilhado com qualquer processo no sistema.When the Global namespace is specified, the synchronization object may be shared with any processes on the system. 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.When the Local namespace is specified, which is also the default when no namespace is specified, the synchronization object may be shared with processes in the same session. 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.On Windows, a session is a login session, and services typically run in a different non-interactive session. Em sistemas operacionais semelhantes ao Unix, cada shell tem sua própria sessão.On Unix-like operating systems, each shell has its own session. Os objetos de sincronização de sessão local podem ser apropriados para sincronizar entre processos com uma relação pai/filho em que todos eles são executados na mesma sessão.Session-local synchronization objects may be appropriate for synchronizing between processes with a parent/child relationship where they all run in the same session. Para obter mais informações sobre nomes de objetos Synchornization no Windows, consulte nomes de objetos.For more information about synchornization object names on Windows, see Object Names.

Se um objeto de sincronização do tipo solicitado existir no namespace, o objeto de sincronização existente será aberto.If a synchronization object of the requested type exists in the namespace, the existing synchronization object is opened. Se um objeto de sincronização não existir no namespace ou se um objeto de sincronização de um tipo diferente existir no namespace, um WaitHandleCannotBeOpenedException será gerado.If a synchronization object does not exist in the namespace, or a synchronization object of a different type exists in the namespace, a WaitHandleCannotBeOpenedException is thrown.

O rights parâmetro deve incluir o EventWaitHandleRights.Synchronize sinalizador para permitir que os threads aguardem o evento e o EventWaitHandleRights.Modify sinalizador para permitir que os threads chamem os Set Reset métodos e.The rights parameter must include the EventWaitHandleRights.Synchronize flag to allow threads to wait on the event, and the EventWaitHandleRights.Modify flag to allow threads to call the Set and Reset methods.

O OpenExisting método tenta abrir um evento de sistema nomeado existente.The OpenExisting method tries to open an existing named system event. Para criar o evento do sistema quando ele ainda não existir, use um dos EventWaitHandle construtores que tem um name parâmetro.To create the system event when it does not already exist, use one of the EventWaitHandle constructors that has a name parameter.

Várias chamadas para esse método que usam o mesmo valor para não name retornam necessariamente o mesmo EventWaitHandle objeto, embora os objetos retornados representem o mesmo evento de sistema nomeado.Multiple calls to this method that use the same value for name do not necessarily return the same EventWaitHandle object, even though the objects that are returned represent the same named system event.

Veja também

Aplica-se a