Mutex.OpenExisting Metodo

Definizione

Apre un mutex denominato specificato, se esistente.

Overload

OpenExisting(String)

Apre il mutex denominato specificato, se esistente.

OpenExisting(String, MutexRights)

Apre il mutex denominato specificato, se esistente, con l'accesso di sicurezza desiderato.

OpenExisting(String)

Apre il mutex denominato specificato, se esistente.

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

Parametri

name
String

Nome dell'oggetto di sincronizzazione da condividere con altri processi. Per il nome è prevista la distinzione tra maiuscole e minuscole. Il carattere della barra rovesciata (\) è riservato e può essere usato solo per specificare uno spazio dei nomi. Per altre informazioni sugli spazi dei nomi, vedere la sezione osservazioni. Potrebbero esserci ulteriori restrizioni sul nome a seconda del sistema operativo. Ad esempio, nei sistemi operativi basati su Unix, il nome dopo l'esclusione dello spazio dei nomi deve essere un nome di file valido.

Restituisce

Oggetto che rappresenta il mutex di sistema denominato.

Attributi

Eccezioni

Il parametro name è una stringa vuota.

-oppure-

Solo .NET Framework: la lunghezza di name supera MAX_PATH (260 caratteri).

name costruito in modo predefinito è null.

Non è possibile creare un oggetto di sincronizzazione con l'elemento name specificato. Un oggetto di sincronizzazione di un tipo diverso potrebbe avere lo stesso nome. In alcuni casi, questa eccezione può essere generata per i nomi non validi.

name non è valido. I motivi possono essere diversi, e tra questi limitazioni implementate dal sistema operativo, come prefisso sconosciuto o caratteri non validi. Si noti che il nome e i prefissi comuni "Global\" e "Local\" sono distinzione tra maiuscole e minuscole.

-oppure-

Si è verificato un altro errore. È possibile che la proprietà HResult offra ulteriori informazioni.

Solo Windows: name ha specificato uno spazio dei nomi sconosciuto. Per altre informazioni, vedere Object Names (Nomi oggetti).

name supera la lunghezza consentita. Le limitazioni di lunghezza possono dipendere dal sistema operativo o dalla configurazione.

Il mutex denominato esiste, ma l'utente non dispone dell'accesso di sicurezza necessario per usarlo.

Esempio

Nell'esempio di codice seguente viene illustrato il comportamento tra processi di un mutex denominato con sicurezza del controllo di accesso. Nell'esempio viene usato l'overload del OpenExisting(String) metodo per testare l'esistenza di un mutex denominato.

Se il mutex non esiste, viene creato con la proprietà iniziale e la sicurezza del controllo di accesso che nega all'utente corrente il diritto di usare il mutex, ma concede il diritto di leggere e modificare le autorizzazioni per il mutex.

Se si esegue l'esempio compilato da due finestre di comando, la seconda copia genererà un'eccezione di violazione di accesso nella chiamata a OpenExisting(String). L'eccezione viene rilevata e l'esempio usa l'overload del metodo per aprire il OpenExisting(String, MutexRights) mutex con i diritti necessari per leggere e modificare le autorizzazioni.

Dopo la modifica delle autorizzazioni, il mutex viene aperto con i diritti necessari per immetterlo e rilasciarlo. Se si esegue l'esempio compilato da una terza finestra di comando, viene eseguito usando le nuove autorizzazioni.

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

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

      Mutex^ m = nullptr;
      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( L"Mutex does not exist." );
         doesNotExist = true;
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"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 = String::Concat( Environment::UserDomainName, L"\\",
            Environment::UserName );
         MutexSecurity^ mSec = gcnew MutexSecurity;

         MutexAccessRule^ rule = gcnew MutexAccessRule( user,
            static_cast<MutexRights>(
               MutexRights::Synchronize |
               MutexRights::Modify),
            AccessControlType::Deny );
         mSec->AddAccessRule( rule );

         rule = gcnew MutexAccessRule( user,
            static_cast<MutexRights>(
               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 = gcnew 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 )
         {
            Console::WriteLine( L"Created the mutex." );
         }
         else
         {
            Console::WriteLine( L"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,
               static_cast<MutexRights>(
                  MutexRights::ReadPermissions |
                  MutexRights::ChangePermissions) );
            
            // Get the current ACL. This requires
            // MutexRights.ReadPermissions.
            MutexSecurity^ mSec = m->GetAccessControl();

            String^ user = String::Concat( Environment::UserDomainName,
               L"\\", Environment::UserName );
            
            // First, the rule that denied the current user
            // the right to enter and release the mutex must
            // be removed.
            MutexAccessRule^ rule = gcnew MutexAccessRule( user,
               static_cast<MutexRights>(
                  MutexRights::Synchronize |
                  MutexRights::Modify),
               AccessControlType::Deny );
            mSec->RemoveAccessRule( rule );
            
            // Now grant the user the correct rights.
            //
            rule = gcnew MutexAccessRule( user,
               static_cast<MutexRights>(
                  MutexRights::Synchronize |
                  MutexRights::Modify),
               AccessControlType::Allow );
            mSec->AddAccessRule( rule );
            
            // Update the ACL. This requires
            // MutexRights.ChangePermissions.
            m->SetAccessControl( mSec );

            Console::WriteLine( L"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(
               L"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( L"Wait for the mutex." );
            m->WaitOne();
            Console::WriteLine( L"Entered the mutex." );
         }
         catch ( UnauthorizedAccessException^ ex ) 
         {
            Console::WriteLine( L"Unauthorized access: {0}",
               ex->Message );
         }
      }

      Console::WriteLine( L"Press the Enter key to exit." );
      Console::ReadLine();
      m->ReleaseMutex();
      m->Dispose();
   }
};

int main()
{
   Example::Main();
}
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

Commenti

Può name essere preceduto da Global\ o Local\ per specificare uno spazio dei nomi. Quando viene specificato lo spazio dei nomi, l'oggetto Global di sincronizzazione può essere condiviso con tutti i processi nel sistema. Quando viene specificato lo Local spazio dei nomi, che è anche il valore predefinito quando non viene specificato alcun spazio dei nomi, l'oggetto di sincronizzazione può essere condiviso con i processi nella stessa sessione. In Windows una sessione è una sessione di accesso e i servizi vengono in genere eseguiti in una sessione non interattiva diversa. Nei sistemi operativi Unix, ogni shell ha la propria sessione. Gli oggetti di sincronizzazione locale della sessione possono essere appropriati per la sincronizzazione tra processi con una relazione padre/figlio in cui vengono eseguiti tutti nella stessa sessione. Per altre informazioni sui nomi degli oggetti di sincronizzazione in Windows, vedere Nomi oggetti.

Se esiste un oggetto di sincronizzazione del tipo richiesto nello spazio dei nomi, l'oggetto di sincronizzazione esistente viene aperto. Se un oggetto di sincronizzazione non esiste nello spazio dei nomi o un oggetto di sincronizzazione di un tipo diverso esiste nello spazio dei nomi, viene generato un WaitHandleCannotBeOpenedException oggetto.

Il OpenExisting metodo tenta di aprire il mutex di sistema specificato. Per creare il mutex di sistema quando non esiste già, usare uno dei Mutex costruttori con un name parametro.

Più chiamate a questo metodo che usano lo stesso valore per name non restituiscono necessariamente lo stesso Mutex oggetto, anche se gli oggetti restituiti rappresentano lo stesso mutex di sistema denominato.

Questo overload di metodo equivale a chiamare l'overload del OpenExisting(String, MutexRights) metodo e specificare MutexRights.Synchronize e MutexRights.Modify diritti, combinati usando l'operazione OR bit per bit.

La specifica del MutexRights.Synchronize flag consente a un thread di attendere il mutex e specificare il flag consente a un thread di chiamare il ReleaseMutexMutexRights.Modify metodo.

Questo metodo non richiede la proprietà del mutex.

Si applica a

OpenExisting(String, MutexRights)

Apre il mutex denominato specificato, se esistente, con l'accesso di sicurezza desiderato.

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

Parametri

name
String

Nome dell'oggetto di sincronizzazione da condividere con altri processi. Per il nome è prevista la distinzione tra maiuscole e minuscole. Il carattere della barra rovesciata (\) è riservato e può essere usato solo per specificare uno spazio dei nomi. Per altre informazioni sugli spazi dei nomi, vedere la sezione osservazioni. Potrebbero esserci ulteriori restrizioni sul nome a seconda del sistema operativo. Ad esempio, nei sistemi operativi basati su Unix, il nome dopo l'esclusione dello spazio dei nomi deve essere un nome di file valido.

rights
MutexRights

Combinazione bit per bit dei valori di enumerazione che rappresentano l'accesso di sicurezza desiderato.

Restituisce

Oggetto che rappresenta il mutex di sistema denominato.

Attributi

Eccezioni

Il parametro name è una stringa vuota.

-oppure-

Solo .NET Framework: la lunghezza di name supera MAX_PATH (260 caratteri).

name costruito in modo predefinito è null.

Non è possibile creare un oggetto di sincronizzazione con l'elemento name specificato. Un oggetto di sincronizzazione di un tipo diverso potrebbe avere lo stesso nome. In alcuni casi, questa eccezione può essere generata per i nomi non validi.

name non è valido. I motivi possono essere diversi, e tra questi limitazioni implementate dal sistema operativo, come prefisso sconosciuto o caratteri non validi. Si noti che il nome e i prefissi comuni "Global\" e "Local\" sono distinzione tra maiuscole e minuscole.

-oppure-

Si è verificato un altro errore. È possibile che la proprietà HResult offra ulteriori informazioni.

Solo Windows: name ha specificato uno spazio dei nomi sconosciuto. Per altre informazioni, vedere Object Names (Nomi oggetti).

name supera la lunghezza consentita. Le limitazioni di lunghezza possono dipendere dal sistema operativo o dalla configurazione.

Il mutex denominato esiste, ma l'utente non dispone dell'accesso di sicurezza desiderato.

Esempio

Nell'esempio di codice seguente viene illustrato il comportamento tra processi di un mutex denominato con sicurezza del controllo di accesso. Nell'esempio viene usato l'overload del OpenExisting(String) metodo per testare l'esistenza di un mutex denominato.

Se il mutex non esiste, viene creato con la proprietà iniziale e la sicurezza del controllo di accesso che nega all'utente corrente il diritto di usare il mutex, ma concede il diritto di leggere e modificare le autorizzazioni per il mutex.

Se si esegue l'esempio compilato da due finestre di comando, la seconda copia genererà un'eccezione di violazione di accesso nella chiamata a OpenExisting(String). L'eccezione viene rilevata e l'esempio usa l'overload del metodo per aprire il OpenExisting(String, MutexRights) mutex con i diritti necessari per leggere e modificare le autorizzazioni.

Dopo la modifica delle autorizzazioni, il mutex viene aperto con i diritti necessari per immetterlo e rilasciarlo. Se si esegue l'esempio compilato da una terza finestra di comando, viene eseguito usando le nuove autorizzazioni.

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

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

      Mutex^ m = nullptr;
      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( L"Mutex does not exist." );
         doesNotExist = true;
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"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 = String::Concat( Environment::UserDomainName, L"\\",
            Environment::UserName );
         MutexSecurity^ mSec = gcnew MutexSecurity;

         MutexAccessRule^ rule = gcnew MutexAccessRule( user,
            static_cast<MutexRights>(
               MutexRights::Synchronize |
               MutexRights::Modify),
            AccessControlType::Deny );
         mSec->AddAccessRule( rule );

         rule = gcnew MutexAccessRule( user,
            static_cast<MutexRights>(
               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 = gcnew 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 )
         {
            Console::WriteLine( L"Created the mutex." );
         }
         else
         {
            Console::WriteLine( L"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,
               static_cast<MutexRights>(
                  MutexRights::ReadPermissions |
                  MutexRights::ChangePermissions) );
            
            // Get the current ACL. This requires
            // MutexRights.ReadPermissions.
            MutexSecurity^ mSec = m->GetAccessControl();

            String^ user = String::Concat( Environment::UserDomainName,
               L"\\", Environment::UserName );
            
            // First, the rule that denied the current user
            // the right to enter and release the mutex must
            // be removed.
            MutexAccessRule^ rule = gcnew MutexAccessRule( user,
               static_cast<MutexRights>(
                  MutexRights::Synchronize |
                  MutexRights::Modify),
               AccessControlType::Deny );
            mSec->RemoveAccessRule( rule );
            
            // Now grant the user the correct rights.
            //
            rule = gcnew MutexAccessRule( user,
               static_cast<MutexRights>(
                  MutexRights::Synchronize |
                  MutexRights::Modify),
               AccessControlType::Allow );
            mSec->AddAccessRule( rule );
            
            // Update the ACL. This requires
            // MutexRights.ChangePermissions.
            m->SetAccessControl( mSec );

            Console::WriteLine( L"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(
               L"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( L"Wait for the mutex." );
            m->WaitOne();
            Console::WriteLine( L"Entered the mutex." );
         }
         catch ( UnauthorizedAccessException^ ex ) 
         {
            Console::WriteLine( L"Unauthorized access: {0}",
               ex->Message );
         }
      }

      Console::WriteLine( L"Press the Enter key to exit." );
      Console::ReadLine();
      m->ReleaseMutex();
      m->Dispose();
   }
};

int main()
{
   Example::Main();
}
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

Commenti

Può name essere preceduto da Global\ o Local\ per specificare uno spazio dei nomi. Quando viene specificato lo spazio dei nomi, l'oggetto Global di sincronizzazione può essere condiviso con tutti i processi nel sistema. Quando viene specificato lo Local spazio dei nomi, che è anche il valore predefinito quando non viene specificato alcun spazio dei nomi, l'oggetto di sincronizzazione può essere condiviso con i processi nella stessa sessione. In Windows una sessione è una sessione di accesso e i servizi vengono in genere eseguiti in una sessione non interattiva diversa. Nei sistemi operativi Unix, ogni shell ha la propria sessione. Gli oggetti di sincronizzazione locale della sessione possono essere appropriati per la sincronizzazione tra processi con una relazione padre/figlio in cui vengono eseguiti tutti nella stessa sessione. Per altre informazioni sui nomi degli oggetti di sincronizzazione in Windows, vedere Nomi oggetti.

Se esiste un oggetto di sincronizzazione del tipo richiesto nello spazio dei nomi, l'oggetto di sincronizzazione esistente viene aperto. Se un oggetto di sincronizzazione non esiste nello spazio dei nomi o un oggetto di sincronizzazione di un tipo diverso esiste nello spazio dei nomi, viene generato un WaitHandleCannotBeOpenedException oggetto.

Il rights parametro deve includere il flag per consentire ai thread di attendere il MutexRights.Synchronize mutex e il MutexRights.Modify flag per consentire ai thread di chiamare il ReleaseMutex metodo.

Il OpenExisting metodo tenta di aprire un mutex denominato esistente. Per creare il mutex di sistema quando non esiste già, usare uno dei Mutex costruttori con un name parametro .

Più chiamate a questo metodo che usano lo stesso valore per name non restituiscono necessariamente lo stesso Mutex oggetto, anche se gli oggetti restituiti rappresentano lo stesso mutex di sistema denominato.

Questo metodo non richiede la proprietà del mutex.

Si applica a