Mutex.OpenExisting Método

Definição

Abre um mutex especificado com nome, se já existir.

Sobrecargas

Name Description
OpenExisting(String)

Abre o mutex nomeado especificado, se já existir.

OpenExisting(String, MutexRights)

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

OpenExisting(String)

Abre o mutex nomeado especificado, se já existir.

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

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 sistema nomeado mutex.

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 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.

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 mutex 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 mutex 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 mutex nomeado.

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

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, MutexRights) sobrecarga de métodos para abrir o mutex com os direitos necessários para ler e alterar as permissões.

Depois de as permissões serem alteradas, o mutex é 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 mutexName = "MutexExample4";

        Mutex m = null;
        bool doesNotExist = false;
        bool unauthorized = false;

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

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

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

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

            MutexAccessRule rule = new MutexAccessRule(user, 
                MutexRights.Synchronize | MutexRights.Modify, 
                AccessControlType.Deny);
            mSec.AddAccessRule(rule);

            rule = new MutexAccessRule(user, 
                MutexRights.ReadPermissions | MutexRights.ChangePermissions,
                AccessControlType.Allow);
            mSec.AddAccessRule(rule);

            // Create a Mutex object that represents the system
            // mutex named by the constant 'mutexName', with
            // initial ownership for this thread, and with the
            // specified security access. The Boolean value that 
            // indicates creation of the underlying system object
            // is placed in mutexWasCreated.
            //
            m = new Mutex(true, mutexName, out mutexWasCreated, mSec);

            // If the named system mutex 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 mutex. Otherwise, exit the program.
            // 
            if (mutexWasCreated)
            {
                Console.WriteLine("Created the mutex.");
            }
            else
            {
                Console.WriteLine("Unable to create the mutex.");
                return;
            }
        }
        else if (unauthorized)
        {
            // Open the mutex to read and change the access control
            // security. The access control security defined above
            // allows the current user to do this.
            //
            try
            {
                m = Mutex.OpenExisting(mutexName, 
                    MutexRights.ReadPermissions | MutexRights.ChangePermissions);

                // Get the current ACL. This requires 
                // MutexRights.ReadPermissions.
                MutexSecurity mSec = m.GetAccessControl();
                
                string user = Environment.UserDomainName + "\\"
                    + Environment.UserName;

                // First, the rule that denied the current user 
                // the right to enter and release the mutex must
                // be removed.
                MutexAccessRule rule = new MutexAccessRule(user, 
                     MutexRights.Synchronize | MutexRights.Modify,
                     AccessControlType.Deny);
                mSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new MutexAccessRule(user, 
                    MutexRights.Synchronize | MutexRights.Modify,
                    AccessControlType.Allow);
                mSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // MutexRights.ChangePermissions.
                m.SetAccessControl(mSec);

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

                // Open the mutex with (MutexRights.Synchronize 
                // | MutexRights.Modify), the rights required to
                // enter and release the mutex.
                //
                m = Mutex.OpenExisting(mutexName);
            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}",
                    ex.Message);
                return;
            }
        }

        // If this program created the mutex, it already owns
        // the mutex.
        //
        if (!mutexWasCreated)
        {
            // Enter the mutex, and hold it until the program
            // exits.
            //
            try
            {
                Console.WriteLine("Wait for the mutex.");
                m.WaitOne();
                Console.WriteLine("Entered the mutex.");
            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unauthorized access: {0}", ex.Message);
            }
        }

        Console.WriteLine("Press the Enter key to exit.");
        Console.ReadLine();
        m.ReleaseMutex();
        m.Dispose();
    }
}
Imports System.Threading
Imports System.Security.AccessControl

Friend Class Example

    <MTAThread> _
    Friend Shared Sub Main()
        Const mutexName As String = "MutexExample4"

        Dim m As Mutex = Nothing
        Dim doesNotExist as Boolean = False
        Dim unauthorized As Boolean = False

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

        ' Attempt to open the named mutex.
        Try
            ' Open the mutex with (MutexRights.Synchronize Or
            ' MutexRights.Modify), to enter and release the
            ' named mutex.
            '
            m = Mutex.OpenExisting(mutexName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Mutex 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 mutex does not exist.
        ' (2) The mutex exists, but the current user doesn't 
        ' have access. (3) The mutex exists and the user has
        ' access.
        '
        If doesNotExist Then
            ' The mutex does not exist, so create it.

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

            Dim rule As New MutexAccessRule(user, _
                MutexRights.Synchronize Or MutexRights.Modify, _
                AccessControlType.Deny)
            mSec.AddAccessRule(rule)

            rule = New MutexAccessRule(user, _
                MutexRights.ReadPermissions Or _
                MutexRights.ChangePermissions, _
                AccessControlType.Allow)
            mSec.AddAccessRule(rule)

            ' Create a Mutex object that represents the system
            ' mutex named by the constant 'mutexName', with
            ' initial ownership for this thread, and with the
            ' specified security access. The Boolean value that 
            ' indicates creation of the underlying system object
            ' is placed in mutexWasCreated.
            '
            m = New Mutex(True, mutexName, mutexWasCreated, mSec)

            ' If the named system mutex 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 mutex. Otherwise, exit the program.
            ' 
            If mutexWasCreated Then
                Console.WriteLine("Created the mutex.")
            Else
                Console.WriteLine("Unable to create the mutex.")
                Return
            End If

        ElseIf unauthorized Then

            ' Open the mutex to read and change the access control
            ' security. The access control security defined above
            ' allows the current user to do this.
            '
            Try
                m = Mutex.OpenExisting(mutexName, _
                    MutexRights.ReadPermissions Or _
                    MutexRights.ChangePermissions)

                ' Get the current ACL. This requires 
                ' MutexRights.ReadPermissions.
                Dim mSec As MutexSecurity = m.GetAccessControl()
                
                Dim user As String = Environment.UserDomainName _ 
                    & "\" & Environment.UserName

                ' First, the rule that denied the current user 
                ' the right to enter and release the mutex must
                ' be removed.
                Dim rule As New MutexAccessRule(user, _
                    MutexRights.Synchronize Or MutexRights.Modify, _
                    AccessControlType.Deny)
                mSec.RemoveAccessRule(rule)

                ' Now grant the user the correct rights.
                ' 
                rule = New MutexAccessRule(user, _
                    MutexRights.Synchronize Or MutexRights.Modify, _
                    AccessControlType.Allow)
                mSec.AddAccessRule(rule)

                ' Update the ACL. This requires
                ' MutexRights.ChangePermissions.
                m.SetAccessControl(mSec)

                Console.WriteLine("Updated mutex security.")

                ' Open the mutex with (MutexRights.Synchronize 
                ' Or MutexRights.Modify), the rights required to
                ' enter and release the mutex.
                '
                m = Mutex.OpenExisting(mutexName)

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

        End If

        ' If this program created the mutex, it already owns
        ' the mutex.
        '
        If Not mutexWasCreated Then
            ' Enter the mutex, and hold it until the program
            ' exits.
            '
            Try
                Console.WriteLine("Wait for the mutex.")
                m.WaitOne()
                Console.WriteLine("Entered the mutex.")
            Catch ex As UnauthorizedAccessException
                Console.WriteLine("Unauthorized access: {0}", _
                    ex.Message)
            End Try
        End If

        Console.WriteLine("Press the Enter key to exit.")
        Console.ReadLine()
        m.ReleaseMutex()
        m.Dispose()
    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 mutex do sistema nomeado especificado. Para criar o mutex do sistema quando ainda não existe, use um dos Mutex 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 Mutex objeto, mesmo que os objetos devolvidos representem o mesmo nome mutex do sistema.

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

Especificar o MutexRights.Synchronize flag permite que um thread espere no mutex, e especificar o MutexRights.Modify flag permite que o thread chame o ReleaseMutex método.

Este método não solicita a posse do mutex.

Aplica-se a

OpenExisting(String, MutexRights)

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

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

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
MutexRights

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 sistema nomeado mutex.

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 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.

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 mutex nomeado existe, mas o utilizador não tem o acesso de segurança desejado.

Exemplos

O exemplo de código seguinte demonstra o comportamento cruzado de processos de um mutex 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 mutex nomeado.

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

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, MutexRights) sobrecarga de métodos para abrir o mutex com os direitos necessários para ler e alterar as permissões.

Depois de as permissões serem alteradas, o mutex é 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 mutexName = "MutexExample4";

        Mutex m = null;
        bool doesNotExist = false;
        bool unauthorized = false;

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

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

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

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

            MutexAccessRule rule = new MutexAccessRule(user, 
                MutexRights.Synchronize | MutexRights.Modify, 
                AccessControlType.Deny);
            mSec.AddAccessRule(rule);

            rule = new MutexAccessRule(user, 
                MutexRights.ReadPermissions | MutexRights.ChangePermissions,
                AccessControlType.Allow);
            mSec.AddAccessRule(rule);

            // Create a Mutex object that represents the system
            // mutex named by the constant 'mutexName', with
            // initial ownership for this thread, and with the
            // specified security access. The Boolean value that 
            // indicates creation of the underlying system object
            // is placed in mutexWasCreated.
            //
            m = new Mutex(true, mutexName, out mutexWasCreated, mSec);

            // If the named system mutex 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 mutex. Otherwise, exit the program.
            // 
            if (mutexWasCreated)
            {
                Console.WriteLine("Created the mutex.");
            }
            else
            {
                Console.WriteLine("Unable to create the mutex.");
                return;
            }
        }
        else if (unauthorized)
        {
            // Open the mutex to read and change the access control
            // security. The access control security defined above
            // allows the current user to do this.
            //
            try
            {
                m = Mutex.OpenExisting(mutexName, 
                    MutexRights.ReadPermissions | MutexRights.ChangePermissions);

                // Get the current ACL. This requires 
                // MutexRights.ReadPermissions.
                MutexSecurity mSec = m.GetAccessControl();
                
                string user = Environment.UserDomainName + "\\"
                    + Environment.UserName;

                // First, the rule that denied the current user 
                // the right to enter and release the mutex must
                // be removed.
                MutexAccessRule rule = new MutexAccessRule(user, 
                     MutexRights.Synchronize | MutexRights.Modify,
                     AccessControlType.Deny);
                mSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new MutexAccessRule(user, 
                    MutexRights.Synchronize | MutexRights.Modify,
                    AccessControlType.Allow);
                mSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // MutexRights.ChangePermissions.
                m.SetAccessControl(mSec);

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

                // Open the mutex with (MutexRights.Synchronize 
                // | MutexRights.Modify), the rights required to
                // enter and release the mutex.
                //
                m = Mutex.OpenExisting(mutexName);
            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}",
                    ex.Message);
                return;
            }
        }

        // If this program created the mutex, it already owns
        // the mutex.
        //
        if (!mutexWasCreated)
        {
            // Enter the mutex, and hold it until the program
            // exits.
            //
            try
            {
                Console.WriteLine("Wait for the mutex.");
                m.WaitOne();
                Console.WriteLine("Entered the mutex.");
            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unauthorized access: {0}", ex.Message);
            }
        }

        Console.WriteLine("Press the Enter key to exit.");
        Console.ReadLine();
        m.ReleaseMutex();
        m.Dispose();
    }
}
Imports System.Threading
Imports System.Security.AccessControl

Friend Class Example

    <MTAThread> _
    Friend Shared Sub Main()
        Const mutexName As String = "MutexExample4"

        Dim m As Mutex = Nothing
        Dim doesNotExist as Boolean = False
        Dim unauthorized As Boolean = False

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

        ' Attempt to open the named mutex.
        Try
            ' Open the mutex with (MutexRights.Synchronize Or
            ' MutexRights.Modify), to enter and release the
            ' named mutex.
            '
            m = Mutex.OpenExisting(mutexName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Mutex 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 mutex does not exist.
        ' (2) The mutex exists, but the current user doesn't 
        ' have access. (3) The mutex exists and the user has
        ' access.
        '
        If doesNotExist Then
            ' The mutex does not exist, so create it.

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

            Dim rule As New MutexAccessRule(user, _
                MutexRights.Synchronize Or MutexRights.Modify, _
                AccessControlType.Deny)
            mSec.AddAccessRule(rule)

            rule = New MutexAccessRule(user, _
                MutexRights.ReadPermissions Or _
                MutexRights.ChangePermissions, _
                AccessControlType.Allow)
            mSec.AddAccessRule(rule)

            ' Create a Mutex object that represents the system
            ' mutex named by the constant 'mutexName', with
            ' initial ownership for this thread, and with the
            ' specified security access. The Boolean value that 
            ' indicates creation of the underlying system object
            ' is placed in mutexWasCreated.
            '
            m = New Mutex(True, mutexName, mutexWasCreated, mSec)

            ' If the named system mutex 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 mutex. Otherwise, exit the program.
            ' 
            If mutexWasCreated Then
                Console.WriteLine("Created the mutex.")
            Else
                Console.WriteLine("Unable to create the mutex.")
                Return
            End If

        ElseIf unauthorized Then

            ' Open the mutex to read and change the access control
            ' security. The access control security defined above
            ' allows the current user to do this.
            '
            Try
                m = Mutex.OpenExisting(mutexName, _
                    MutexRights.ReadPermissions Or _
                    MutexRights.ChangePermissions)

                ' Get the current ACL. This requires 
                ' MutexRights.ReadPermissions.
                Dim mSec As MutexSecurity = m.GetAccessControl()
                
                Dim user As String = Environment.UserDomainName _ 
                    & "\" & Environment.UserName

                ' First, the rule that denied the current user 
                ' the right to enter and release the mutex must
                ' be removed.
                Dim rule As New MutexAccessRule(user, _
                    MutexRights.Synchronize Or MutexRights.Modify, _
                    AccessControlType.Deny)
                mSec.RemoveAccessRule(rule)

                ' Now grant the user the correct rights.
                ' 
                rule = New MutexAccessRule(user, _
                    MutexRights.Synchronize Or MutexRights.Modify, _
                    AccessControlType.Allow)
                mSec.AddAccessRule(rule)

                ' Update the ACL. This requires
                ' MutexRights.ChangePermissions.
                m.SetAccessControl(mSec)

                Console.WriteLine("Updated mutex security.")

                ' Open the mutex with (MutexRights.Synchronize 
                ' Or MutexRights.Modify), the rights required to
                ' enter and release the mutex.
                '
                m = Mutex.OpenExisting(mutexName)

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

        End If

        ' If this program created the mutex, it already owns
        ' the mutex.
        '
        If Not mutexWasCreated Then
            ' Enter the mutex, and hold it until the program
            ' exits.
            '
            Try
                Console.WriteLine("Wait for the mutex.")
                m.WaitOne()
                Console.WriteLine("Entered the mutex.")
            Catch ex As UnauthorizedAccessException
                Console.WriteLine("Unauthorized access: {0}", _
                    ex.Message)
            End Try
        End If

        Console.WriteLine("Press the Enter key to exit.")
        Console.ReadLine()
        m.ReleaseMutex()
        m.Dispose()
    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 o MutexRights.Synchronize flag para permitir que os threads esperem no mutex, e o MutexRights.Modify flag para permitir que os threads chamem o ReleaseMutex método.

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

Este método não solicita a posse do mutex.

Aplica-se a