EventWaitHandle.OpenExisting Método

Definição

Abre um evento de sincronização especificado com nome, se já existir.

Sobrecargas

Name Description
OpenExisting(String)

Abre o evento de sincronização especificado, se já existir.

OpenExisting(String, EventWaitHandleRights)

Abre o evento de sincronização especificado com nome, se já existir, com o acesso de segurança desejado.

OpenExisting(String)

Abre o evento de sincronização especificado, se já existir.

public:
 static System::Threading::EventWaitHandle ^ OpenExisting(System::String ^ name);
[System.Security.SecurityCritical]
public static System.Threading.EventWaitHandle OpenExisting(string name);
public static System.Threading.EventWaitHandle OpenExisting(string name);
[<System.Security.SecurityCritical>]
static member OpenExisting : string -> System.Threading.EventWaitHandle
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 partilhado com outros processos. O nome é sensível a maiúsculas e minúsculas. O carácter barra inversa (\) é reservado e só pode ser usado para especificar um namespace. Para mais informações sobre namespaces, consulte a secção de observações. Pode haver restrições adicionais ao nome dependendo do sistema operativo. Por exemplo, em sistemas operativos baseados em Unix, o nome após excluir o espaço de nomes deve ser um nome de ficheiro válido.

Devoluções

Um objeto que representa o evento do sistema nomeado.

Atributos

Exceções

Um objeto de sincronização com o fornecido name não pode ser aberto. Pode não existir, ou um objeto de sincronização de outro tipo pode ter o mesmo nome. Em alguns casos, esta exceção pode ser lançada para nomes inválidos.

name é uma corda vazia.

-ou-

.NET Framework apenas: name é mais longo que MAX_PATH (260 caracteres).

name é null.

name é inválido. Isto pode dever-se a várias razões, incluindo algumas restrições que podem ser impostas pelo sistema operativo, como um prefixo desconhecido ou caracteres inválidos. Note que o nome e os prefixos comuns "Global\" e "Local\" são sensíveis a maiúsculas minúsculas.

-ou-

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

Windows apenas: name especificava um namespace desconhecido. Consulte Nomes dos Objetos para mais informações.

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

O evento nomeado existe, mas o utilizador não tem o acesso de segurança necessário para o utilizar.

Observações

Podem name ser precedidos por Global\ ou Local\ para especificar um namespace. Quando o Global namespace é especificado, o objeto de sincronização pode ser partilhado com quaisquer processos no sistema. Quando o Local namespace é especificado, que também é o padrão quando não há namespace especificado, o objeto de sincronização pode ser partilhado com processos na mesma sessão. No Windows, uma sessão é uma sessão de login, e os serviços normalmente correm numa sessão diferente e não interativa. Em sistemas operativos do tipo Unix, cada shell tem a sua própria sessão. Objetos de sincronização local de sessão podem ser apropriados para sincronizar processos com uma relação pai/filho, onde todos correm na mesma sessão. Para mais informações sobre nomes de objetos de sincronização no Windows, veja Object Names.

Se existir um objeto de sincronização do tipo solicitado no namespace, o objeto de sincronização existente é aberto. Se um objeto de sincronização não existir no namespace, ou se existir um objeto de sincronização de outro tipo no namespace, um WaitHandleCannotBeOpenedException é lançado.

O OpenExisting método tenta abrir o evento de sistema nomeado especificado. Para criar o evento do sistema quando este ainda não existe, use um dos EventWaitHandle construtores que tenha um name parâmetro.

Múltiplas chamadas a este método que usam o mesmo valor para name não retornam necessariamente o mesmo EventWaitHandle objeto, embora os objetos que são devolvidos representem o mesmo evento do sistema nomeado.

No .NET Framework, esta sobrecarga de métodos equivale a chamar os direitos de método System.Threading.EventWaitHandle.OpenExisting(System.String,System.Security.AccessControl.EventWaitHandleRights) e especificar EventWaitHandleRights.Synchronize e EventWaitHandleRights.Modify direitos, combinados usando a operação bit a bit OR.

Especificar a EventWaitHandleRights.Synchronize flag permite que uma thread espere pelo evento do sistema nomeado, e especificar a EventWaitHandleRights.Modify flag permite que a thread chame os Set métodos and Reset .

Ver também

Aplica-se a

OpenExisting(String, EventWaitHandleRights)

Abre o evento de sincronização especificado com nome, se já existir, com o acesso de segurança desejado.

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 partilhado com outros processos. O nome é sensível a maiúsculas e minúsculas. O carácter barra inversa (\) é reservado e só pode ser usado para especificar um namespace. Para mais informações sobre namespaces, consulte a secção de observações. Pode haver restrições adicionais ao nome dependendo do sistema operativo. Por exemplo, em sistemas operativos baseados em Unix, o nome após excluir o espaço de nomes deve ser um nome de ficheiro válido.

rights
EventWaitHandleRights

Uma combinação bit a bit dos valores de enumeração que representam o acesso de segurança desejado.

Devoluções

Um objeto que representa o evento do sistema nomeado.

Atributos

Exceções

name é uma corda vazia.

-ou-

.NET Framework apenas: name é mais longo que MAX_PATH (260 caracteres).

name é null.

Um objeto de sincronização com o fornecido name não pode ser aberto. Pode não existir, ou um objeto de sincronização de outro tipo pode ter o mesmo nome. Em alguns casos, esta exceção pode ser lançada para nomes inválidos.

name é inválido. Isto pode dever-se a várias razões, incluindo algumas restrições que podem ser impostas pelo sistema operativo, como um prefixo desconhecido ou caracteres inválidos. Note que o nome e os prefixos comuns "Global\" e "Local\" são sensíveis a maiúsculas minúsculas.

-ou-

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

Windows apenas: name especificava um namespace desconhecido. Consulte Nomes dos Objetos para mais informações.

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

O evento nomeado existe, mas o utilizador não tem o acesso de segurança desejado.

Exemplos

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

Se o evento não existir, é criado com propriedade inicial e segurança de controlo de acessos que nega ao utilizador atual o direito de usar o evento, mas concede o direito de ler e alterar permissões sobre o evento.

Se executares o exemplo compilado a partir de duas janelas de comandos, a segunda cópia irá lançar uma exceção de violação de acesso na chamada para OpenExisting(String). A exceção é apanhada, e o exemplo usa a OpenExisting(String, EventWaitHandleRights) sobrecarga de métodos para esperar pelo evento com os direitos necessários para ler e alterar as permissões.

Depois de as permissões serem alteradas, o evento é aberto com os direitos necessários para esperar e sinalizá-lo. Se executares o exemplo compilado a partir de uma terceira janela de comandos, o exemplo é executado usando as novas permissões.

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

Observações

Podem name ser precedidos por Global\ ou Local\ para especificar um namespace. Quando o Global namespace é especificado, o objeto de sincronização pode ser partilhado com quaisquer processos no sistema. Quando o Local namespace é especificado, que também é o padrão quando não há namespace especificado, o objeto de sincronização pode ser partilhado com processos na mesma sessão. No Windows, uma sessão é uma sessão de login, e os serviços normalmente correm numa sessão diferente e não interativa. Em sistemas operativos do tipo Unix, cada shell tem a sua própria sessão. Objetos de sincronização local de sessão podem ser apropriados para sincronizar processos com uma relação pai/filho, onde todos correm na mesma sessão. Para mais informações sobre nomes de objetos de sincronização no Windows, veja Object Names.

Se existir um objeto de sincronização do tipo solicitado no namespace, o objeto de sincronização existente é aberto. Se um objeto de sincronização não existir no namespace, ou se existir um objeto de sincronização de outro tipo no namespace, um WaitHandleCannotBeOpenedException é lançado.

O rights parâmetro deve incluir a EventWaitHandleRights.Synchronize flag para permitir que as threads esperem pelo evento, e a EventWaitHandleRights.Modify flag para permitir que as threads chamem os Set métodos e.Reset

O OpenExisting método tenta abrir um evento de sistema nomeado existente. Para criar o evento do sistema quando este ainda não existe, use um dos EventWaitHandle construtores que tenha um name parâmetro.

Múltiplas chamadas a este método que usam o mesmo valor para name não retornam necessariamente o mesmo EventWaitHandle objeto, embora os objetos que são devolvidos representem o mesmo evento do sistema nomeado.

Ver também

Aplica-se a