Semaphore.OpenExisting Método

Definição

Abre um semáforo nomeado especificado, se este já existir.

Sobrecargas

Name Description
OpenExisting(String)

Abre o semáforo nomeado especificado, se este já existir.

OpenExisting(String, SemaphoreRights)

Abre o semáforo nomeado especificado, se já existir, com o acesso de segurança desejado.

OpenExisting(String)

Abre o semáforo nomeado especificado, se este já existir.

public:
 static System::Threading::Semaphore ^ OpenExisting(System::String ^ name);
public static System.Threading.Semaphore OpenExisting(string name);
static member OpenExisting : string -> System.Threading.Semaphore
Public Shared Function OpenExisting (name As String) As Semaphore

Parâmetros

name
String

O nome do objeto de sincronização a ser partilhado com outros processos. O nome é sensível a maiúsculas e minúsculas. O carácter de 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. Podem existir restrições adicionais quanto 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 semáforo do sistema nomeado.

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 criado. Um objeto de sincronização de outro tipo pode ter o mesmo nome. Em alguns casos, esta exceção pode ser aplicada a 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.

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

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

Exemplos

O exemplo de código seguinte demonstra o comportamento cruzado de processos de um semáforo nomeado com segurança de controlo de acessos. O exemplo utiliza o OpenExisting(String) método overload para testar a existência de um semáforo nomeado.

Se o semáforo não existir, é criado com uma contagem máxima de dois e com segurança de controlo de acesso que nega ao utilizador atual o direito de usar o semáforo, mas que concede o direito de ler e alterar permissões sobre o semáforo.

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 a OpenExisting(String) sobrecarga de métodos. A exceção é apanhada, e o exemplo usa a OpenExisting(String, SemaphoreRights) sobrecarga do método para abrir o semáforo com os direitos necessários para ler e alterar as permissões.

Depois de alteradas as permissões, o semáforo é aberto com os direitos necessários para entrar e libertá-lo. Se executares o exemplo compilado a partir de uma terceira janela de comandos, ele é executado usando as novas permissões.

using System;
using System.Threading;
using System.Security.AccessControl;

internal class Example
{
    internal static void Main()
    {
        const string semaphoreName = "SemaphoreExample5";

        Semaphore sem = null;
        bool doesNotExist = false;
        bool unauthorized = false;

        // Attempt to open the named semaphore.
        try
        {
            // Open the semaphore with (SemaphoreRights.Synchronize
            // | SemaphoreRights.Modify), to enter and release the
            // named semaphore.
            //
            sem = Semaphore.OpenExisting(semaphoreName);
        }
        catch(WaitHandleCannotBeOpenedException)
        {
            Console.WriteLine("Semaphore does not exist.");
            doesNotExist = true;
        }
        catch(UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
            unauthorized = true;
        }

        // There are three cases: (1) The semaphore does not exist.
        // (2) The semaphore exists, but the current user doesn't 
        // have access. (3) The semaphore exists and the user has
        // access.
        //
        if (doesNotExist)
        {
            // The semaphore does not exist, so create it.
            //
            // The value of this variable is set by the semaphore
            // constructor. It is true if the named system semaphore was
            // created, and false if the named semaphore already existed.
            //
            bool semaphoreWasCreated;

            // Create an access control list (ACL) that denies the
            // current user the right to enter or release the 
            // semaphore, but allows the right to read and change
            // security information for the semaphore.
            //
            string user = Environment.UserDomainName + "\\" 
                + Environment.UserName;
            SemaphoreSecurity semSec = new SemaphoreSecurity();

            SemaphoreAccessRule rule = new SemaphoreAccessRule(
                user, 
                SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                AccessControlType.Deny);
            semSec.AddAccessRule(rule);

            rule = new SemaphoreAccessRule(
                user, 
                SemaphoreRights.ReadPermissions | SemaphoreRights.ChangePermissions,
                AccessControlType.Allow);
            semSec.AddAccessRule(rule);

            // Create a Semaphore object that represents the system
            // semaphore named by the constant 'semaphoreName', with
            // maximum count three, initial count three, and the
            // specified security access. The Boolean value that 
            // indicates creation of the underlying system object is
            // placed in semaphoreWasCreated.
            //
            sem = new Semaphore(3, 3, semaphoreName, 
                out semaphoreWasCreated, semSec);

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

                // Get the current ACL. This requires 
                // SemaphoreRights.ReadPermissions.
                SemaphoreSecurity semSec = sem.GetAccessControl();
                
                string user = Environment.UserDomainName + "\\" 
                    + Environment.UserName;

                // First, the rule that denied the current user 
                // the right to enter and release the semaphore must
                // be removed.
                SemaphoreAccessRule rule = new SemaphoreAccessRule(
                    user, 
                    SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                    AccessControlType.Deny);
                semSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new SemaphoreAccessRule(user, 
                     SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                     AccessControlType.Allow);
                semSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // SemaphoreRights.ChangePermissions.
                sem.SetAccessControl(semSec);

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

                // Open the semaphore with (SemaphoreRights.Synchronize 
                // | SemaphoreRights.Modify), the rights required to
                // enter and release the semaphore.
                //
                sem = Semaphore.OpenExisting(semaphoreName);
            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}", ex.Message);
                return;
            }
        }

        // Enter the semaphore, and hold it until the program
        // exits.
        //
        try
        {
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore.");
            Console.WriteLine("Press the Enter key to exit.");
            Console.ReadLine();
            sem.Release();
        }
        catch(UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
        }
    }
}
Imports System.Threading
Imports System.Security.AccessControl

Friend Class Example

    <MTAThread> _
    Friend Shared Sub Main()
        Const semaphoreName As String = "SemaphoreExample5"

        Dim sem As Semaphore = Nothing
        Dim doesNotExist as Boolean = False
        Dim unauthorized As Boolean = False

        ' Attempt to open the named semaphore.
        Try
            ' Open the semaphore with (SemaphoreRights.Synchronize
            ' Or SemaphoreRights.Modify), to enter and release the
            ' named semaphore.
            '
            sem = Semaphore.OpenExisting(semaphoreName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Semaphore 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 semaphore does not exist.
        ' (2) The semaphore exists, but the current user doesn't 
        ' have access. (3) The semaphore exists and the user has
        ' access.
        '
        If doesNotExist Then
            ' The semaphore does not exist, so create it.
            '
            ' The value of this variable is set by the semaphore
            ' constructor. It is True if the named system semaphore was
            ' created, and False if the named semaphore already existed.
            '
            Dim semaphoreWasCreated As Boolean

            ' Create an access control list (ACL) that denies the
            ' current user the right to enter or release the 
            ' semaphore, but allows the right to read and change
            ' security information for the semaphore.
            '
            Dim user As String = Environment.UserDomainName _ 
                & "\" & Environment.UserName
            Dim semSec As New SemaphoreSecurity()

            Dim rule As New SemaphoreAccessRule(user, _
                SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
                AccessControlType.Deny)
            semSec.AddAccessRule(rule)

            rule = New SemaphoreAccessRule(user, _
                SemaphoreRights.ReadPermissions Or _
                SemaphoreRights.ChangePermissions, _
                AccessControlType.Allow)
            semSec.AddAccessRule(rule)

            ' Create a Semaphore object that represents the system
            ' semaphore named by the constant 'semaphoreName', with
            ' maximum count three, initial count three, and the
            ' specified security access. The Boolean value that 
            ' indicates creation of the underlying system object is
            ' placed in semaphoreWasCreated.
            '
            sem = New Semaphore(3, 3, semaphoreName, _
                semaphoreWasCreated, semSec)

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

        ElseIf unauthorized Then

            ' Open the semaphore to read and change the access
            ' control security. The access control security defined
            ' above allows the current user to do this.
            '
            Try
                sem = Semaphore.OpenExisting(semaphoreName, _
                    SemaphoreRights.ReadPermissions Or _
                    SemaphoreRights.ChangePermissions)

                ' Get the current ACL. This requires 
                ' SemaphoreRights.ReadPermissions.
                Dim semSec As SemaphoreSecurity = sem.GetAccessControl()
                
                Dim user As String = Environment.UserDomainName _ 
                    & "\" & Environment.UserName

                ' First, the rule that denied the current user 
                ' the right to enter and release the semaphore must
                ' be removed.
                Dim rule As New SemaphoreAccessRule(user, _
                    SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
                    AccessControlType.Deny)
                semSec.RemoveAccessRule(rule)

                ' Now grant the user the correct rights.
                ' 
                rule = New SemaphoreAccessRule(user, _
                    SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
                    AccessControlType.Allow)
                semSec.AddAccessRule(rule)

                ' Update the ACL. This requires
                ' SemaphoreRights.ChangePermissions.
                sem.SetAccessControl(semSec)

                Console.WriteLine("Updated semaphore security.")

                ' Open the semaphore with (SemaphoreRights.Synchronize 
                ' Or SemaphoreRights.Modify), the rights required to
                ' enter and release the semaphore.
                '
                sem = Semaphore.OpenExisting(semaphoreName)

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

        End If

        ' Enter the semaphore, and hold it until the program
        ' exits.
        '
        Try
            sem.WaitOne()
            Console.WriteLine("Entered the semaphore.")
            Console.WriteLine("Press the Enter key to exit.")
            Console.ReadLine()
            sem.Release()
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", _
                ex.Message)
        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. Os objetos de sincronização local da sessão podem ser apropriados para sincronizar entre 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 semáforo nomeado especificado. Para criar o semáforo do sistema quando este ainda não existe, use um dos Semaphore 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 Semaphore objeto, embora os objetos que são devolvidos representem o mesmo semáforo do sistema com o mesmo nome.

Esta sobrecarga de métodos é equivalente a chamar o OpenExisting método overload e especificar SemaphoreRights.Synchronize e os direitos SemaphoreRights.Modify , combinados usando a operação OR bit a bit.

Especificar o SemaphoreRights.Synchronize flag permite que um thread entre no semáforo, e especificar o SemaphoreRights.Modify flag permite que um thread chame o Release método.

Ver também

Aplica-se a

OpenExisting(String, SemaphoreRights)

Abre o semáforo nomeado especificado, se já existir, com o acesso de segurança desejado.

public:
 static System::Threading::Semaphore ^ OpenExisting(System::String ^ name, System::Security::AccessControl::SemaphoreRights rights);
public static System.Threading.Semaphore OpenExisting(string name, System.Security.AccessControl.SemaphoreRights rights);
static member OpenExisting : string * System.Security.AccessControl.SemaphoreRights -> System.Threading.Semaphore
Public Shared Function OpenExisting (name As String, rights As SemaphoreRights) As Semaphore

Parâmetros

name
String

O nome do objeto de sincronização a ser partilhado com outros processos. O nome é sensível a maiúsculas e minúsculas. O carácter de 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. Podem existir restrições adicionais quanto 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
SemaphoreRights

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 semáforo do sistema nomeado.

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 criado. Um objeto de sincronização de outro tipo pode ter o mesmo nome. Em alguns casos, esta exceção pode ser aplicada a 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.

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

O semáforo nomeado existe, mas o utilizador não tem os direitos de acesso de segurança desejados.

Exemplos

O exemplo de código seguinte demonstra o comportamento cruzado de processos de um semáforo nomeado com segurança de controlo de acessos. O exemplo utiliza o OpenExisting(String) método overload para testar a existência de um semáforo nomeado.

Se o semáforo não existir, é criado com uma contagem máxima de dois e com uma segurança de controlo de acesso que nega ao utilizador atual o direito de usar o semáforo, mas concede o direito de ler e alterar permissões sobre o semáforo.

Se executares o exemplo compilado a partir de duas janelas de comandos, a segunda cópia lançará uma exceção de violação de acesso na chamada ao OpenExisting(String) método. A exceção é apanhada, e o exemplo usa a OpenExisting(String, SemaphoreRights) sobrecarga do método para abrir o semáforo com os direitos necessários para ler e alterar as permissões.

Depois de alteradas as permissões, o semáforo é aberto com os direitos necessários para entrar e libertá-lo. Se executares o exemplo compilado a partir de uma terceira janela de comandos, ele é executado usando as novas permissões.

using System;
using System.Threading;
using System.Security.AccessControl;

internal class Example
{
    internal static void Main()
    {
        const string semaphoreName = "SemaphoreExample5";

        Semaphore sem = null;
        bool doesNotExist = false;
        bool unauthorized = false;

        // Attempt to open the named semaphore.
        try
        {
            // Open the semaphore with (SemaphoreRights.Synchronize
            // | SemaphoreRights.Modify), to enter and release the
            // named semaphore.
            //
            sem = Semaphore.OpenExisting(semaphoreName);
        }
        catch(WaitHandleCannotBeOpenedException)
        {
            Console.WriteLine("Semaphore does not exist.");
            doesNotExist = true;
        }
        catch(UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
            unauthorized = true;
        }

        // There are three cases: (1) The semaphore does not exist.
        // (2) The semaphore exists, but the current user doesn't 
        // have access. (3) The semaphore exists and the user has
        // access.
        //
        if (doesNotExist)
        {
            // The semaphore does not exist, so create it.
            //
            // The value of this variable is set by the semaphore
            // constructor. It is true if the named system semaphore was
            // created, and false if the named semaphore already existed.
            //
            bool semaphoreWasCreated;

            // Create an access control list (ACL) that denies the
            // current user the right to enter or release the 
            // semaphore, but allows the right to read and change
            // security information for the semaphore.
            //
            string user = Environment.UserDomainName + "\\" 
                + Environment.UserName;
            SemaphoreSecurity semSec = new SemaphoreSecurity();

            SemaphoreAccessRule rule = new SemaphoreAccessRule(
                user, 
                SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                AccessControlType.Deny);
            semSec.AddAccessRule(rule);

            rule = new SemaphoreAccessRule(
                user, 
                SemaphoreRights.ReadPermissions | SemaphoreRights.ChangePermissions,
                AccessControlType.Allow);
            semSec.AddAccessRule(rule);

            // Create a Semaphore object that represents the system
            // semaphore named by the constant 'semaphoreName', with
            // maximum count three, initial count three, and the
            // specified security access. The Boolean value that 
            // indicates creation of the underlying system object is
            // placed in semaphoreWasCreated.
            //
            sem = new Semaphore(3, 3, semaphoreName, 
                out semaphoreWasCreated, semSec);

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

                // Get the current ACL. This requires 
                // SemaphoreRights.ReadPermissions.
                SemaphoreSecurity semSec = sem.GetAccessControl();
                
                string user = Environment.UserDomainName + "\\" 
                    + Environment.UserName;

                // First, the rule that denied the current user 
                // the right to enter and release the semaphore must
                // be removed.
                SemaphoreAccessRule rule = new SemaphoreAccessRule(
                    user, 
                    SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                    AccessControlType.Deny);
                semSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new SemaphoreAccessRule(user, 
                     SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                     AccessControlType.Allow);
                semSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // SemaphoreRights.ChangePermissions.
                sem.SetAccessControl(semSec);

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

                // Open the semaphore with (SemaphoreRights.Synchronize 
                // | SemaphoreRights.Modify), the rights required to
                // enter and release the semaphore.
                //
                sem = Semaphore.OpenExisting(semaphoreName);
            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}", ex.Message);
                return;
            }
        }

        // Enter the semaphore, and hold it until the program
        // exits.
        //
        try
        {
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore.");
            Console.WriteLine("Press the Enter key to exit.");
            Console.ReadLine();
            sem.Release();
        }
        catch(UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
        }
    }
}
Imports System.Threading
Imports System.Security.AccessControl

Friend Class Example

    <MTAThread> _
    Friend Shared Sub Main()
        Const semaphoreName As String = "SemaphoreExample5"

        Dim sem As Semaphore = Nothing
        Dim doesNotExist as Boolean = False
        Dim unauthorized As Boolean = False

        ' Attempt to open the named semaphore.
        Try
            ' Open the semaphore with (SemaphoreRights.Synchronize
            ' Or SemaphoreRights.Modify), to enter and release the
            ' named semaphore.
            '
            sem = Semaphore.OpenExisting(semaphoreName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Semaphore 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 semaphore does not exist.
        ' (2) The semaphore exists, but the current user doesn't 
        ' have access. (3) The semaphore exists and the user has
        ' access.
        '
        If doesNotExist Then
            ' The semaphore does not exist, so create it.
            '
            ' The value of this variable is set by the semaphore
            ' constructor. It is True if the named system semaphore was
            ' created, and False if the named semaphore already existed.
            '
            Dim semaphoreWasCreated As Boolean

            ' Create an access control list (ACL) that denies the
            ' current user the right to enter or release the 
            ' semaphore, but allows the right to read and change
            ' security information for the semaphore.
            '
            Dim user As String = Environment.UserDomainName _ 
                & "\" & Environment.UserName
            Dim semSec As New SemaphoreSecurity()

            Dim rule As New SemaphoreAccessRule(user, _
                SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
                AccessControlType.Deny)
            semSec.AddAccessRule(rule)

            rule = New SemaphoreAccessRule(user, _
                SemaphoreRights.ReadPermissions Or _
                SemaphoreRights.ChangePermissions, _
                AccessControlType.Allow)
            semSec.AddAccessRule(rule)

            ' Create a Semaphore object that represents the system
            ' semaphore named by the constant 'semaphoreName', with
            ' maximum count three, initial count three, and the
            ' specified security access. The Boolean value that 
            ' indicates creation of the underlying system object is
            ' placed in semaphoreWasCreated.
            '
            sem = New Semaphore(3, 3, semaphoreName, _
                semaphoreWasCreated, semSec)

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

        ElseIf unauthorized Then

            ' Open the semaphore to read and change the access
            ' control security. The access control security defined
            ' above allows the current user to do this.
            '
            Try
                sem = Semaphore.OpenExisting(semaphoreName, _
                    SemaphoreRights.ReadPermissions Or _
                    SemaphoreRights.ChangePermissions)

                ' Get the current ACL. This requires 
                ' SemaphoreRights.ReadPermissions.
                Dim semSec As SemaphoreSecurity = sem.GetAccessControl()
                
                Dim user As String = Environment.UserDomainName _ 
                    & "\" & Environment.UserName

                ' First, the rule that denied the current user 
                ' the right to enter and release the semaphore must
                ' be removed.
                Dim rule As New SemaphoreAccessRule(user, _
                    SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
                    AccessControlType.Deny)
                semSec.RemoveAccessRule(rule)

                ' Now grant the user the correct rights.
                ' 
                rule = New SemaphoreAccessRule(user, _
                    SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
                    AccessControlType.Allow)
                semSec.AddAccessRule(rule)

                ' Update the ACL. This requires
                ' SemaphoreRights.ChangePermissions.
                sem.SetAccessControl(semSec)

                Console.WriteLine("Updated semaphore security.")

                ' Open the semaphore with (SemaphoreRights.Synchronize 
                ' Or SemaphoreRights.Modify), the rights required to
                ' enter and release the semaphore.
                '
                sem = Semaphore.OpenExisting(semaphoreName)

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

        End If

        ' Enter the semaphore, and hold it until the program
        ' exits.
        '
        Try
            sem.WaitOne()
            Console.WriteLine("Entered the semaphore.")
            Console.WriteLine("Press the Enter key to exit.")
            Console.ReadLine()
            sem.Release()
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", _
                ex.Message)
        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. Os objetos de sincronização local da sessão podem ser apropriados para sincronizar entre 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 SemaphoreRights.Synchronize flag para permitir que as threads entrem no semáforo, e a SemaphoreRights.Modify flag para permitir que as threads chamem o Release método.

O OpenExisting método tenta abrir um semáforo nomeado existente. Para criar o semáforo do sistema quando este ainda não existe, use um dos Semaphore 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 Semaphore objeto, embora os objetos que são devolvidos representem o mesmo semáforo do sistema com o mesmo nome.

Ver também

Aplica-se a