Mutex Costruttori

Definizione

Inizializza una nuova istanza della classe Mutex.Initializes a new instance of the Mutex class.

Overload

Mutex()

Inizializza una nuova istanza della classe Mutex con le proprietà predefinite.Initializes a new instance of the Mutex class with default properties.

Mutex(Boolean)

Inizializza una nuova istanza della classe Mutex con un valore Boolean che indica se il thread chiamante deve avere la proprietà iniziale del mutex.Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex.

Mutex(Boolean, String)

Inizializza una nuova istanza della classe Mutex con un valore booleano che indica se il thread chiamante deve avere la proprietà iniziale del mutex e con una stringa che rappresenta il nome del mutex.Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, and a string that is the name of the mutex.

Mutex(Boolean, String, Boolean)

Inizializza una nuova istanza della classe Mutex con un valore booleano che indica se il thread chiamante deve avere la proprietà iniziale del mutex, con una stringa che rappresenta il nome del mutex e con un valore booleano che, quando il metodo viene restituito, indichi se al thread chiamante era stata concessa la proprietà iniziale del mutex.Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, a string that is the name of the mutex, and a Boolean value that, when the method returns, indicates whether the calling thread was granted initial ownership of the mutex.

Mutex(Boolean, String, Boolean, MutexSecurity)

Inizializza una nuova istanza della classe Mutex con un valore booleano che indica se il thread chiamante deve avere la proprietà iniziale del mutex, con una stringa che rappresenta il nome del mutex, con una variabile Boolean che, quando il metodo viene restituito, indichi se al thread chiamante era stata concessa la proprietà iniziale del mutex e con la sicurezza del controllo di accesso da applicare al mutex denominato.Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, a string that is the name of the mutex, a Boolean variable that, when the method returns, indicates whether the calling thread was granted initial ownership of the mutex, and the access control security to be applied to the named mutex.

Mutex()

Inizializza una nuova istanza della classe Mutex con le proprietà predefinite.Initializes a new instance of the Mutex class with default properties.

public:
 Mutex();
public Mutex ();
Public Sub New ()

Esempi

Nell'esempio di codice riportato di seguito viene Mutex illustrato come utilizzare un oggetto locale per sincronizzare l'accesso a una risorsa protetta.The following code example shows how a local Mutex object is used to synchronize access to a protected resource. Il thread che crea il mutex non è il proprietario iniziale.The thread that creates the mutex does not own it initially.

// This example shows how a Mutex is used to synchronize access
// to a protected resource. Unlike Monitor, Mutex can be used with
// WaitHandle.WaitAll and WaitAny, and can be passed across
// AppDomain boundaries.
using namespace System;
using namespace System::Threading;
const int numIterations = 1;
const int numThreads = 3;
ref class Test
{
public:

   // Create a new Mutex. The creating thread does not own the
   // Mutex.
   static Mutex^ mut = gcnew Mutex;
   static void MyThreadProc()
   {
      for ( int i = 0; i < numIterations; i++ )
      {
         UseResource();

      }
   }


private:

   // This method represents a resource that must be synchronized
   // so that only one thread at a time can enter.
   static void UseResource()
   {
      
      //Wait until it is OK to enter.
      mut->WaitOne();
      Console::WriteLine( "{0} has entered protected the area", Thread::CurrentThread->Name );
      
      // Place code to access non-reentrant resources here.
      // Simulate some work.
      Thread::Sleep( 500 );
      Console::WriteLine( "{0} is leaving protected the area\r\n", Thread::CurrentThread->Name );
      
      // Release the Mutex.
      mut->ReleaseMutex();
   }

};

int main()
{
   
   // Create the threads that will use the protected resource.
   for ( int i = 0; i < numThreads; i++ )
   {
      Thread^ myThread = gcnew Thread( gcnew ThreadStart( Test::MyThreadProc ) );
      myThread->Name = String::Format( "Thread {0}", i + 1 );
      myThread->Start();

   }
   
   // The main thread exits, but the application continues to 
   // run until all foreground threads have exited.
}

// This example shows how a Mutex is used to synchronize access
// to a protected resource. Unlike Monitor, Mutex can be used with
// WaitHandle.WaitAll and WaitAny, and can be passed across
// AppDomain boundaries.
 
using System;
using System.Threading;

class Test
{
    // Create a new Mutex. The creating thread does not own the
    // Mutex.
    private static Mutex mut = new Mutex();
    private const int numIterations = 1;
    private const int numThreads = 3;

    static void Main()
    {
        // Create the threads that will use the protected resource.
        for(int i = 0; i < numThreads; i++)
        {
            Thread myThread = new Thread(new ThreadStart(MyThreadProc));
            myThread.Name = String.Format("Thread{0}", i + 1);
            myThread.Start();
        }

        // The main thread exits, but the application continues to
        // run until all foreground threads have exited.
    }

    private static void MyThreadProc()
    {
        for(int i = 0; i < numIterations; i++)
        {
            UseResource();
        }
    }

    // This method represents a resource that must be synchronized
    // so that only one thread at a time can enter.
    private static void UseResource()
    {
        // Wait until it is safe to enter.
        mut.WaitOne();

        Console.WriteLine("{0} has entered the protected area", 
            Thread.CurrentThread.Name);

        // Place code to access non-reentrant resources here.

        // Simulate some work.
        Thread.Sleep(500);

        Console.WriteLine("{0} is leaving the protected area\r\n", 
            Thread.CurrentThread.Name);
         
        // Release the Mutex.
        mut.ReleaseMutex();
    }
}
' This example shows how a Mutex is used to synchronize access
' to a protected resource. Unlike Monitor, Mutex can be used with
' WaitHandle.WaitAll and WaitAny, and can be passed across
' AppDomain boundaries.
 
Imports System.Threading

Class Test
    ' Create a new Mutex. The creating thread does not own the
    ' Mutex.
    Private Shared mut As New Mutex()
    Private Const numIterations As Integer = 1
    Private Const numThreads As Integer = 3

    <MTAThread> _
    Shared Sub Main()
        ' Create the threads that will use the protected resource.
        Dim i As Integer
        For i = 1 To numThreads
            Dim myThread As New Thread(AddressOf MyThreadProc)
            myThread.Name = [String].Format("Thread{0}", i)
            myThread.Start()
        Next i

        ' The main thread exits, but the application continues to
        ' run until all foreground threads have exited.

    End Sub

    Private Shared Sub MyThreadProc()
        Dim i As Integer
        For i = 1 To numIterations
            UseResource()
        Next i
    End Sub

    ' This method represents a resource that must be synchronized
    ' so that only one thread at a time can enter.
    Private Shared Sub UseResource()
        ' Wait until it is safe to enter.
        mut.WaitOne()

        Console.WriteLine("{0} has entered protected area", _
            Thread.CurrentThread.Name)

        ' Place code to access non-reentrant resources here.

        ' Simulate some work
        Thread.Sleep(500)

        Console.WriteLine("{0} is leaving protected area" & vbCrLf, _
            Thread.CurrentThread.Name)

        ' Release Mutex.
        mut.ReleaseMutex()
    End Sub
End Class

Commenti

La chiamata a questo overload del costruttore equivale alla chiamata Mutex(Boolean) dell'overload del costruttore false e alla specifica della proprietà iniziale del mutex.Calling this constructor overload is the same as calling the Mutex(Boolean) constructor overload and specifying false for initial ownership of the mutex. Ovvero il thread chiamante non è il proprietario del mutex.That is, the calling thread does not own the mutex.

Vedi anche

Mutex(Boolean)

Inizializza una nuova istanza della classe Mutex con un valore Boolean che indica se il thread chiamante deve avere la proprietà iniziale del mutex.Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex.

public:
 Mutex(bool initiallyOwned);
public Mutex (bool initiallyOwned);
new System.Threading.Mutex : bool -> System.Threading.Mutex
Public Sub New (initiallyOwned As Boolean)

Parametri

initiallyOwned
Boolean

Viene restituito true per concedere al thread chiamante la proprietà iniziale del mutex; in caso contrario, false.true to give the calling thread initial ownership of the mutex; otherwise, false.

Esempi

Nell'esempio di codice riportato di seguito viene Mutex illustrato come utilizzare un oggetto locale per sincronizzare l'accesso a una risorsa protetta.The following code example shows how a local Mutex object is used to synchronize access to a protected resource. Il thread che crea l' Mutex oggetto lo possiede inizialmente.The thread that creates the Mutex owns it initially.

using namespace System;
using namespace System::Threading;

const int numIterations = 1;
const int numThreads = 3;

ref class Test
{
public:

   // Create a new Mutex. The creating thread owns the
   // Mutex.
   static Mutex^ mut = gcnew Mutex( true );
   static void MyThreadProc()
   {
      for ( int i = 0; i < numIterations; i++ )
      {
         UseResource();

      }
   }


private:

   // This method represents a resource that must be synchronized
   // so that only one thread at a time can enter.
   static void UseResource()
   {
      
      //Wait until it is OK to enter.
      mut->WaitOne();
      Console::WriteLine( "{0} has entered protected the area", Thread::CurrentThread->Name );
      
      // Place code to access non-reentrant resources here.
      // Simulate some work.
      Thread::Sleep( 500 );
      Console::WriteLine( "{0} is leaving protected the area\r\n", Thread::CurrentThread->Name );
      
      // Release the Mutex.
      mut->ReleaseMutex();
   }

};

int main()
{
   
   // Initialize the Mutex.
   Mutex^ mut = Test::mut;
   
   // Create the threads that will use the protected resource.
   for ( int i = 0; i < numThreads; i++ )
   {
      Thread^ myThread = gcnew Thread( gcnew ThreadStart( Test::MyThreadProc ) );
      myThread->Name = String::Format( "Thread {0}", i + 1 );
      myThread->Start();

   }
   
   // Wait one second before allowing other threads to
   // acquire the Mutex.
   Console::WriteLine( "Creating thread owns the Mutex." );
   Thread::Sleep( 1000 );
   Console::WriteLine( "Creating thread releases the Mutex.\r\n" );
   mut->ReleaseMutex();
}
// The example displays output like the following:
//       Creating thread owns the Mutex.
//       Creating thread releases the Mutex.
//       
//       Thread1 has entered the protected area
//       Thread1 is leaving the protected area
//       
//       Thread2 has entered the protected area
//       Thread2 is leaving the protected area
//       
//       Thread3 has entered the protected area
//       Thread3 is leaving the protected area
using System;
using System.Threading;

class Test
{
    // Create a new Mutex. The creating thread owns the Mutex.
    private static Mutex mut = new Mutex(true);
    private const int numIterations = 1;
    private const int numThreads = 3;

    static void Main()
    {
        // Create the threads that will use the protected resource.
        for(int i = 0; i < numThreads; i++)
        {
            Thread myThread = new Thread(new ThreadStart(MyThreadProc));
            myThread.Name = String.Format("Thread{0}", i + 1);
            myThread.Start();
        }

        // Wait one second before allowing other threads to
        // acquire the Mutex.
        Console.WriteLine("Creating thread owns the Mutex.");
        Thread.Sleep(1000);

        Console.WriteLine("Creating thread releases the Mutex.\r\n");
        mut.ReleaseMutex();
    }

    private static void MyThreadProc()
    {
        for(int i = 0; i < numIterations; i++)
        {
            UseResource();
        }
    }

    // This method represents a resource that must be synchronized
    // so that only one thread at a time can enter.
    private static void UseResource()
    {
        // Wait until it is safe to enter.
        mut.WaitOne();

        Console.WriteLine("{0} has entered the protected area", 
            Thread.CurrentThread.Name);

        // Place code to access non-reentrant resources here.

        // Simulate some work.
        Thread.Sleep(500);

        Console.WriteLine("{0} is leaving the protected area\r\n", 
            Thread.CurrentThread.Name);
         
        // Release the Mutex.
        mut.ReleaseMutex();
    }
}
// The example displays output like the following:
//       Creating thread owns the Mutex.
//       Creating thread releases the Mutex.
//       
//       Thread1 has entered the protected area
//       Thread1 is leaving the protected area
//       
//       Thread2 has entered the protected area
//       Thread2 is leaving the protected area
//       
//       Thread3 has entered the protected area
//       Thread3 is leaving the protected area
Imports System.Threading

Class Test
    ' Create a new Mutex. The creating thread owns the
    ' Mutex.
    Private Shared mut As New Mutex(True)
    Private Const numIterations As Integer = 1
    Private Const numThreads As Integer = 3

    <MTAThread> _
    Shared Sub Main()
        ' Create the threads that will use the protected resource.
        Dim i As Integer
        For i = 1 To numThreads
            Dim myThread As New Thread(AddressOf MyThreadProc)
            myThread.Name = [String].Format("Thread{0}", i)
            myThread.Start()
        Next i

        ' Wait one second before allowing other threads to
        ' acquire the Mutex.
        Console.WriteLine("Creating thread owns the Mutex.")
        Thread.Sleep(1000)

        Console.WriteLine("Creating thread releases the Mutex." & vbCrLf)
        mut.ReleaseMutex()
    End Sub

    Private Shared Sub MyThreadProc()
        Dim i As Integer
        For i = 1 To numIterations
            UseResource()
        Next i
    End Sub

    ' This method represents a resource that must be synchronized
    ' so that only one thread at a time can enter.
    Private Shared Sub UseResource()
        ' Wait until it is safe to enter.
        mut.WaitOne()

        Console.WriteLine("{0} has entered protected area", _
            Thread.CurrentThread.Name)

        ' Place code to access non-reentrant resources here.

        ' Simulate some work
        Thread.Sleep(500)

        Console.WriteLine("{0} is leaving protected area" & vbCrLf, _
            Thread.CurrentThread.Name)

        ' Release Mutex.
        mut.ReleaseMutex()
    End Sub
End Class
' The example displays output like the following:
'       Creating thread owns the Mutex.
'       Creating thread releases the Mutex.
'       
'       Thread1 has entered the protected area
'       Thread1 is leaving the protected area
'       
'       Thread2 has entered the protected area
'       Thread2 is leaving the protected area
'       
'       Thread3 has entered the protected area
'       Thread3 is leaving the protected area

Vedi anche

Mutex(Boolean, String)

Inizializza una nuova istanza della classe Mutex con un valore booleano che indica se il thread chiamante deve avere la proprietà iniziale del mutex e con una stringa che rappresenta il nome del mutex.Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, and a string that is the name of the mutex.

public:
 Mutex(bool initiallyOwned, System::String ^ name);
[System.Security.SecurityCritical]
public Mutex (bool initiallyOwned, string name);
new System.Threading.Mutex : bool * string -> System.Threading.Mutex
Public Sub New (initiallyOwned As Boolean, name As String)

Parametri

initiallyOwned
Boolean

true per concedere al thread chiamante la proprietà iniziale del mutex di sistema denominato, se questo è stato creato come risultato della chiamata; in caso contrario, false.true to give the calling thread initial ownership of the named system mutex if the named system mutex is created as a result of this call; otherwise, false.

name
String

Nome di Mutex.The name of the Mutex. Se il valore è null, l'oggetto Mutex è senza nome.If the value is null, the Mutex is unnamed.

Attributi

Eccezioni

Il mutex denominato esiste e ha accesso alla sicurezza controllo, ma l'utente non dispone di FullControl.The named mutex exists and has access control security, but the user does not have FullControl.

Errore Win32.A Win32 error occurred.

Il mutex denominato non può essere creato, forse perché un handle di attesa di un tipo diverso ha lo stesso nome.The named mutex cannot be created, perhaps because a wait handle of a different type has the same name.

La lunghezza di name supera i 260 caratteri.name is longer than 260 characters.

Esempi

Nell'esempio seguente viene illustrato come un mutex denominato viene utilizzato per segnalare tra thread in esecuzione in due processi distinti.The following example shows how a named mutex is used to signal between threads running in two separate processes.

Eseguire questo programma da due o più finestre di comando.Run this program from two or more command windows. Ogni processo crea un Mutex oggetto che rappresenta il mutex MyMutexdenominato.Each process creates a Mutex object that represents the named mutex MyMutex. Il mutex denominato è un oggetto di sistema la cui durata è vincolata dalle durate degli Mutex oggetti che lo rappresentano.The named mutex is a system object whose lifetime is bounded by the lifetimes of the Mutex objects that represent it. Il mutex denominato viene creato quando il primo processo crea il Mutex relativo oggetto. in questo esempio, il mutex denominato è di proprietà del primo processo che esegue il programma.The named mutex is created when the first process creates its Mutex object; in this example, the named mutex is owned by the first process that runs the program. Il mutex denominato viene eliminato definitivamente quando tutti Mutex gli oggetti che lo rappresentano sono stati rilasciati.The named mutex is destroyed when all the Mutex objects that represent it have been released.

L'overload del costruttore utilizzato in questo esempio non è in grado di indicare al thread chiamante se è stata concessa la proprietà iniziale del mutex denominato.The constructor overload used in this example cannot tell the calling thread whether initial ownership of the named mutex was granted. Non usare questo costruttore per richiedere la proprietà iniziale, a meno che non sia possibile essere certi che il thread creerà il mutex denominato.You should not use this constructor to request initial ownership unless you can be certain that the thread will create the named mutex.

using namespace System;
using namespace System::Threading;

int main()
{
   // Create the named mutex. Only one system object named 
   // "MyMutex" can exist; the local Mutex object represents 
   // this system object, regardless of which process or thread
   // caused "MyMutex" to be created.
   Mutex^ m = gcnew Mutex( false,"MyMutex" );
   
   // Try to gain control of the named mutex. If the mutex is 
   // controlled by another thread, wait for it to be released.        
   Console::WriteLine(  "Waiting for the Mutex." );
   m->WaitOne();
   
   // Keep control of the mutex until the user presses
   // ENTER.
   Console::WriteLine( "This application owns the mutex. "
   "Press ENTER to release the mutex and exit." );
   Console::ReadLine();
   m->ReleaseMutex();
}

using System;
using System.Threading;

public class Test
{
    public static void Main()
    {
        // Create the named mutex. Only one system object named 
        // "MyMutex" can exist; the local Mutex object represents 
        // this system object, regardless of which process or thread
        // caused "MyMutex" to be created.
        Mutex m = new Mutex(false, "MyMutex");
        
        // Try to gain control of the named mutex. If the mutex is 
        // controlled by another thread, wait for it to be released.        
        Console.WriteLine("Waiting for the Mutex.");
        m.WaitOne();

        // Keep control of the mutex until the user presses
        // ENTER.
        Console.WriteLine("This application owns the mutex. " +
            "Press ENTER to release the mutex and exit.");
        Console.ReadLine();

        m.ReleaseMutex();
    }
}
Imports System.Threading

Public Class Test
   Public Shared Sub Main()
      ' Create the named mutex. Only one system object named 
      ' "MyMutex" can exist; the local Mutex object represents 
      ' this system object, regardless of which process or thread
      ' caused "MyMutex" to be created.
      Dim m As New Mutex(False, "MyMutex")
      
      ' Try to gain control of the named mutex. If the mutex is 
      ' controlled by another thread, wait for it to be released.        
      Console.WriteLine("Waiting for the Mutex.")
      m.WaitOne()
      
      ' Keep control of the mutex until the user presses
      ' ENTER.
      Console.WriteLine("This application owns the mutex. " _
          & "Press ENTER to release the mutex and exit.")
      Console.ReadLine()
      
      m.ReleaseMutex()
   End Sub 
End Class 

Commenti

Se name non null è e initiallyOwned ètrue, il thread chiamante è proprietario del mutex solo se il mutex di sistema denominato è stato creato come risultato della chiamata.If name is not null and initiallyOwned is true, the calling thread owns the mutex only if the named system mutex was created as a result of this call. Poiché non esiste alcun meccanismo per determinare se il mutex di sistema denominato è stato creato, è preferibile initiallyOwned specificare false per quando si chiama questo overload del costruttore.Since there is no mechanism for determining whether the named system mutex was created, it is better to specify false for initiallyOwned when calling this constructor overload. È possibile utilizzare il Mutex(Boolean, String, Boolean) costruttore se è necessario determinare la proprietà iniziale.You can use the Mutex(Boolean, String, Boolean) constructor if you need to determine initial ownership.

Questo costruttore inizializza un Mutex oggetto che rappresenta un mutex di sistema denominato.This constructor initializes a Mutex object that represents a named system mutex. È possibile creare più Mutex oggetti che rappresentano lo stesso mutex di sistema denominato.You can create multiple Mutex objects that represent the same named system mutex.

Se il mutex denominato è già stato creato con la sicurezza del controllo di accesso e il chiamante non MutexRights.FullControldispone di, viene generata un'eccezione.If the named mutex has already been created with access control security, and the caller does not have MutexRights.FullControl, an exception is thrown. Per aprire un mutex denominato esistente con solo le autorizzazioni necessarie per la sincronizzazione delle attività dei thread, OpenExisting vedere il metodo.To open an existing named mutex with only those permissions needed for synchronizing thread activities, see the OpenExisting method.

Se si specifica null o una stringa vuota per name, viene creato un mutex locale, come se fosse stato chiamato il Mutex(Boolean) costruttore.If you specify null or an empty string for name, a local mutex is created, as if you had called the Mutex(Boolean) constructor. In questo caso, createdNew è sempre true.In this case, createdNew is always true.

Poiché sono a livello di sistema, i mutex denominati possono essere usati per coordinare l'uso delle risorse tra i limiti dei processi.Because they are system-wide, named mutexes can be used to coordinate resource use across process boundaries.

Nota

In un server che esegue Servizi terminal, un mutex di sistema denominato può avere due livelli di visibilità.On a server that is running Terminal Services, a named system mutex can have two levels of visibility. Se il nome inizia con il prefisso "globale\", il mutex è visibile in tutte le sessioni di Terminal Server.If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. Se il nome inizia con il prefisso "Local\", il mutex è visibile solo nella sessione di Terminal Server in cui è stato creato.If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created. In tal caso, è possibile che esista un mutex separato con lo stesso nome in ogni altra sessione di Terminal Server sul server.In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server. Se non si specifica un prefisso quando si crea un mutex denominato, prende il prefisso "Local\".If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\". All'interno di una sessione di Terminal Server, due mutex i cui nomi differiscono solo per i rispettivi prefissi sono mutex distinti ed entrambi sono visibili a tutti i processi nella sessione Terminal Server.Within a terminal server session, two mutexes whose names differ only by their prefixes are separate mutexes, and both are visible to all processes in the terminal server session. Ovvero i nomi di prefisso "Global\" e "Local\" descrivono l'ambito del nome mutex rispetto alle sessioni di Terminal Server, non rispetto ai processi.That is, the prefix names "Global\" and "Local\" describe the scope of the mutex name relative to terminal server sessions, not relative to processes.

La barra rovesciata (\) è un carattere riservato in un nome di mutex.The backslash (\) is a reserved character in a mutex name. Non usare una barra rovesciata (\) in un nome del mutex, se non come specificato nella nota sull'uso dei mutex nelle sessioni di Terminal Server.Don't use a backslash (\) in a mutex name except as specified in the note on using mutexes in terminal server sessions. In caso contrario, potrebbe essere generata una DirectoryNotFoundException, anche se il nome del mutex rappresenta un file esistente.Otherwise, a DirectoryNotFoundException may be thrown, even though the name of the mutex represents an existing file.

Sicurezza

SecurityCriticalAttribute
richiede l'attendibilità totale per il chiamante immediato.Requires full trust for the immediate caller. Questo membro non può essere utilizzato da codice parzialmente attendibile o trasparente.This member cannot be used by partially trusted or transparent code.

Vedi anche

Mutex(Boolean, String, Boolean)

Inizializza una nuova istanza della classe Mutex con un valore booleano che indica se il thread chiamante deve avere la proprietà iniziale del mutex, con una stringa che rappresenta il nome del mutex e con un valore booleano che, quando il metodo viene restituito, indichi se al thread chiamante era stata concessa la proprietà iniziale del mutex.Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, a string that is the name of the mutex, and a Boolean value that, when the method returns, indicates whether the calling thread was granted initial ownership of the mutex.

public:
 Mutex(bool initiallyOwned, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew);
[System.Security.SecurityCritical]
public Mutex (bool initiallyOwned, string name, out bool createdNew);
new System.Threading.Mutex : bool * string * bool -> System.Threading.Mutex
Public Sub New (initiallyOwned As Boolean, name As String, ByRef createdNew As Boolean)

Parametri

initiallyOwned
Boolean

true per concedere al thread chiamante la proprietà iniziale del mutex di sistema denominato, se questo è stato creato come risultato della chiamata; in caso contrario, false.true to give the calling thread initial ownership of the named system mutex if the named system mutex is created as a result of this call; otherwise, false.

name
String

Nome di Mutex.The name of the Mutex. Se il valore è null, l'oggetto Mutex è senza nome.If the value is null, the Mutex is unnamed.

createdNew
Boolean

Quando questo metodo viene restituito, contiene un valore booleano che è true se è stato creato un mutex locale (ovvero, se il valore di name è null o una stringa vuota) oppure se è stato creato il mutex di sistema denominato specificato; false se il mutex di sistema denominato specificato è già esistente.When this method returns, contains a Boolean that is true if a local mutex was created (that is, if name is null or an empty string) or if the specified named system mutex was created; false if the specified named system mutex already existed. Questo parametro viene passato non inizializzato.This parameter is passed uninitialized.

Attributi

Eccezioni

Il mutex denominato esiste e ha accesso alla sicurezza controllo, ma l'utente non dispone di FullControl.The named mutex exists and has access control security, but the user does not have FullControl.

Errore Win32.A Win32 error occurred.

Il mutex denominato non può essere creato, forse perché un handle di attesa di un tipo diverso ha lo stesso nome.The named mutex cannot be created, perhaps because a wait handle of a different type has the same name.

La lunghezza di name supera i 260 caratteri.name is longer than 260 characters.

Esempi

Nell'esempio di codice seguente viene illustrato come un mutex denominato viene utilizzato per segnalare tra processi o thread.The following code example shows how a named mutex is used to signal between processes or threads. Eseguire questo programma da due o più finestre di comando.Run this program from two or more command windows. Ogni processo crea un Mutex oggetto che rappresenta il mutex denominato "mutex".Each process creates a Mutex object that represents the named mutex "MyMutex". Il mutex denominato è un oggetto di sistema.The named mutex is a system object. In questo esempio, la sua durata è limitata dalle durate degli Mutex oggetti che lo rappresentano.In this example, its lifetime is bounded by the lifetimes of the Mutex objects that represent it. Il mutex denominato viene creato quando il primo processo crea il relativo Mutex oggetto locale e viene eliminato definitivamente quando Mutex tutti gli oggetti che lo rappresentano sono stati rilasciati.The named mutex is created when the first process creates its local Mutex object, and destroyed when all the Mutex objects that represent it have been released. Il mutex denominato è inizialmente di proprietà del primo processo.The named mutex is initially owned by the first process. Il secondo processo e tutti i processi successivi attendono che i processi precedenti rilascino il mutex denominato.The second process and any subsequent processes wait for earlier processes to release the named mutex.

// This example shows how a named mutex is used to signal between
// processes or threads.
// Run this program from two (or more) command windows. Each process
// creates a Mutex object that represents the named mutex "MyMutex".
// The named mutex is a system object whose lifetime is bounded by the
// lifetimes of the Mutex objects that represent it. The named mutex
// is created when the first process creates its local Mutex; in this
// example, the named mutex is owned by the first process. The named 
// mutex is destroyed when all the Mutex objects that represent it
// have been released. 
// The second process (and any subsequent process) waits for earlier
// processes to release the named mutex.
using namespace System;
using namespace System::Threading;
int main()
{
   
   // Set this variable to false if you do not want to request 
   // initial ownership of the named mutex.
   bool requestInitialOwnership = true;
   bool mutexWasCreated;
   
   // Request initial ownership of the named mutex by passing
   // true for the first parameter. Only one system object named 
   // "MyMutex" can exist; the local Mutex object represents 
   // this system object. If "MyMutex" is created by this call,
   // then mutexWasCreated contains true; otherwise, it contains
   // false.
   Mutex^ m = gcnew Mutex( requestInitialOwnership, "MyMutex", mutexWasCreated );
   
   // This thread owns the mutex only if it both requested 
   // initial ownership and created the named mutex. Otherwise,
   // it can request the named mutex by calling WaitOne.
   if (  !(requestInitialOwnership && mutexWasCreated) )
   {
      Console::WriteLine(  "Waiting for the named mutex." );
      m->WaitOne();
   }

   
   // Once the process has gained control of the named mutex,
   // hold onto it until the user presses ENTER.
   Console::WriteLine(  "This process owns the named mutex. "
    "Press ENTER to release the mutex and exit." );
   Console::ReadLine();
   
   // Call ReleaseMutex to allow other threads to gain control
   // of the named mutex. If you keep a reference to the local
   // Mutex, you can call WaitOne to request control of the 
   // named mutex.
   m->ReleaseMutex();
}

// This example shows how a named mutex is used to signal between
// processes or threads.
// Run this program from two (or more) command windows. Each process
// creates a Mutex object that represents the named mutex "MyMutex".
// The named mutex is a system object whose lifetime is bounded by the
// lifetimes of the Mutex objects that represent it. The named mutex
// is created when the first process creates its local Mutex; in this
// example, the named mutex is owned by the first process. The named 
// mutex is destroyed when all the Mutex objects that represent it
// have been released. 
// The second process (and any subsequent process) waits for earlier
// processes to release the named mutex.

using System;
using System.Threading;

public class Test
{
    public static void Main()
    {
        // Set this variable to false if you do not want to request 
        // initial ownership of the named mutex.
        bool requestInitialOwnership = true;
        bool mutexWasCreated;

        // Request initial ownership of the named mutex by passing
        // true for the first parameter. Only one system object named 
        // "MyMutex" can exist; the local Mutex object represents 
        // this system object. If "MyMutex" is created by this call,
        // then mutexWasCreated contains true; otherwise, it contains
        // false.
        Mutex m = new Mutex(requestInitialOwnership, 
                            "MyMutex", 
                            out mutexWasCreated);
        
        // This thread owns the mutex only if it both requested 
        // initial ownership and created the named mutex. Otherwise,
        // it can request the named mutex by calling WaitOne.
        if (!(requestInitialOwnership && mutexWasCreated))
        {
            Console.WriteLine("Waiting for the named mutex.");
            m.WaitOne();
        }

        // Once the process has gained control of the named mutex,
        // hold onto it until the user presses ENTER.
        Console.WriteLine("This process owns the named mutex. " +
            "Press ENTER to release the mutex and exit.");
        Console.ReadLine();

        // Call ReleaseMutex to allow other threads to gain control
        // of the named mutex. If you keep a reference to the local
        // Mutex, you can call WaitOne to request control of the 
        // named mutex.
        m.ReleaseMutex();
    }
}
' This example shows how a named mutex is used to signal between
' processes or threads.
' Run this program from two (or more) command windows. Each process
' creates a Mutex object that represents the named mutex "MyMutex".
' The named mutex is a system object whose lifetime is bounded by the
' lifetimes of the Mutex objects that represent it. The named mutex
' is created when the first process creates its local Mutex; in this
' example, the named mutex is owned by the first process. The named 
' mutex is destroyed when all the Mutex objects that represent it
' have been released. 
' The second process (and any subsequent process) waits for earlier
' processes to release the named mutex.

Imports System.Threading

Public Class Test
   
   <MTAThread> _
   Public Shared Sub Main()
      ' Set this variable to false if you do not want to request 
      ' initial ownership of the named mutex.
      Dim requestInitialOwnership As Boolean = True
      Dim mutexWasCreated As Boolean
      
      ' Request initial ownership of the named mutex by passing
      ' true for the first parameter. Only one system object named 
      ' "MyMutex" can exist; the local Mutex object represents 
      ' this system object. If "MyMutex" is created by this call,
      ' then mutexWasCreated contains true; otherwise, it contains
      ' false.
      Dim m As New Mutex(requestInitialOwnership, "MyMutex", _
          mutexWasCreated)
      
      ' This thread owns the mutex only if it both requested 
      ' initial ownership and created the named mutex. Otherwise,
      ' it can request the named mutex by calling WaitOne.
      If Not (requestInitialOwnership And mutexWasCreated) Then
         Console.WriteLine("Waiting for the named mutex.")
         m.WaitOne()
      End If
      
      ' Once the process has gained control of the named mutex,
      ' hold onto it until the user presses ENTER.
      Console.WriteLine("This process owns the named mutex. " _
          & "Press ENTER to release the mutex and exit.")
      Console.ReadLine()
      
      ' Call ReleaseMutex to allow other threads to gain control
      ' of the named mutex. If you keep a reference to the local
      ' Mutex, you can call WaitOne to request control of the 
      ' named mutex.
      m.ReleaseMutex()
   End Sub
End Class

Commenti

Se name initiallyOwned non createdNew true è e ètrue, il thread chiamante è proprietario del mutex denominato solo se si trova dopo la chiamata a. nullIf name is not null and initiallyOwned is true, the calling thread owns the named mutex only if createdNew is true after the call. In caso contrario, il thread può richiedere il mutex WaitOne chiamando il metodo.Otherwise the thread can request the mutex by calling the WaitOne method.

Questo costruttore inizializza un Mutex oggetto che rappresenta un mutex di sistema denominato.This constructor initializes a Mutex object that represents a named system mutex. È possibile creare più Mutex oggetti che rappresentano lo stesso mutex di sistema denominato.You can create multiple Mutex objects that represent the same named system mutex.

Se il mutex denominato è già stato creato con la sicurezza del controllo di accesso e il chiamante non MutexRights.FullControl dispone dei diritti, viene generata un'eccezione.If the named mutex has already been created with access control security, and the caller does not have MutexRights.FullControl rights, an exception is thrown. Per aprire un mutex denominato esistente con solo le autorizzazioni necessarie per la sincronizzazione delle attività dei thread, OpenExisting vedere il metodo.To open an existing named mutex with only those permissions needed for synchronizing thread activities, see the OpenExisting method.

Se si specifica null o una stringa vuota per name, viene creato un mutex locale, come se fosse stato chiamato il Mutex(Boolean) costruttore.If you specify null or an empty string for name, a local mutex is created, as if you had called the Mutex(Boolean) constructor. In questo caso, createdNew è sempre true.In this case, createdNew is always true.

Poiché sono a livello di sistema, i mutex denominati possono essere usati per coordinare l'uso delle risorse tra i limiti dei processi.Because they are system-wide, named mutexes can be used to coordinate resource use across process boundaries.

Nota

In un server che esegue Servizi terminal, un mutex di sistema denominato può avere due livelli di visibilità.On a server that is running Terminal Services, a named system mutex can have two levels of visibility. Se il nome inizia con il prefisso "globale\", il mutex è visibile in tutte le sessioni di Terminal Server.If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. Se il nome inizia con il prefisso "Local\", il mutex è visibile solo nella sessione di Terminal Server in cui è stato creato.If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created. In tal caso, è possibile che esista un mutex separato con lo stesso nome in ogni altra sessione di Terminal Server sul server.In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server. Se non si specifica un prefisso quando si crea un mutex denominato, prende il prefisso "Local\".If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\". All'interno di una sessione di Terminal Server, due mutex i cui nomi differiscono solo per i rispettivi prefissi sono mutex distinti ed entrambi sono visibili a tutti i processi nella sessione Terminal Server.Within a terminal server session, two mutexes whose names differ only by their prefixes are separate mutexes, and both are visible to all processes in the terminal server session. Ovvero i nomi di prefisso "Global\" e "Local\" descrivono l'ambito del nome mutex rispetto alle sessioni di Terminal Server, non rispetto ai processi.That is, the prefix names "Global\" and "Local\" describe the scope of the mutex name relative to terminal server sessions, not relative to processes.

La barra rovesciata (\) è un carattere riservato in un nome di mutex.The backslash (\) is a reserved character in a mutex name. Non usare una barra rovesciata (\) in un nome del mutex, se non come specificato nella nota sull'uso dei mutex nelle sessioni di Terminal Server.Don't use a backslash (\) in a mutex name except as specified in the note on using mutexes in terminal server sessions. In caso contrario, potrebbe essere generata una DirectoryNotFoundException, anche se il nome del mutex rappresenta un file esistente.Otherwise, a DirectoryNotFoundException may be thrown, even though the name of the mutex represents an existing file.

Sicurezza

SecurityCriticalAttribute
richiede l'attendibilità totale per il chiamante immediato.Requires full trust for the immediate caller. Questo membro non può essere utilizzato da codice parzialmente attendibile o trasparente.This member cannot be used by partially trusted or transparent code.

Vedi anche

Mutex(Boolean, String, Boolean, MutexSecurity)

Inizializza una nuova istanza della classe Mutex con un valore booleano che indica se il thread chiamante deve avere la proprietà iniziale del mutex, con una stringa che rappresenta il nome del mutex, con una variabile Boolean che, quando il metodo viene restituito, indichi se al thread chiamante era stata concessa la proprietà iniziale del mutex e con la sicurezza del controllo di accesso da applicare al mutex denominato.Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, a string that is the name of the mutex, a Boolean variable that, when the method returns, indicates whether the calling thread was granted initial ownership of the mutex, and the access control security to be applied to the named mutex.

public:
 Mutex(bool initiallyOwned, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew, System::Security::AccessControl::MutexSecurity ^ mutexSecurity);
[System.Security.SecurityCritical]
public Mutex (bool initiallyOwned, string name, out bool createdNew, System.Security.AccessControl.MutexSecurity mutexSecurity);
new System.Threading.Mutex : bool * string * bool * System.Security.AccessControl.MutexSecurity -> System.Threading.Mutex

Parametri

initiallyOwned
Boolean

true per concedere al thread chiamante la proprietà iniziale del mutex di sistema denominato, se questo è stato creato come risultato della chiamata; in caso contrario, false.true to give the calling thread initial ownership of the named system mutex if the named system mutex is created as a result of this call; otherwise, false.

name
String

Nome del mutex di sistema.The name of the system mutex. Se il valore è null, l'oggetto Mutex è senza nome.If the value is null, the Mutex is unnamed.

createdNew
Boolean

Quando questo metodo viene restituito, contiene un valore booleano che è true se è stato creato un mutex locale (ovvero, se il valore di name è null o una stringa vuota) oppure se è stato creato il mutex di sistema denominato specificato; false se il mutex di sistema denominato specificato è già esistente.When this method returns, contains a Boolean that is true if a local mutex was created (that is, if name is null or an empty string) or if the specified named system mutex was created; false if the specified named system mutex already existed. Questo parametro viene passato non inizializzato.This parameter is passed uninitialized.

mutexSecurity
MutexSecurity

Oggetto MutexSecurity che rappresenta la sicurezza del controllo di accesso da applicare al mutex di sistema denominato.A MutexSecurity object that represents the access control security to be applied to the named system mutex.

Attributi

Eccezioni

Errore Win32.A Win32 error occurred.

Il mutex denominato esiste e ha accesso alla sicurezza controllo, ma l'utente non dispone di FullControl.The named mutex exists and has access control security, but the user does not have FullControl.

Il mutex denominato non può essere creato, forse perché un handle di attesa di un tipo diverso ha lo stesso nome.The named mutex cannot be created, perhaps because a wait handle of a different type has the same name.

La lunghezza di name supera i 260 caratteri.name is longer than 260 characters.

Esempi

Nell'esempio di codice seguente viene illustrato il comportamento tra processi di un mutex denominato con sicurezza del controllo di accesso.The following code example demonstrates the cross-process behavior of a named mutex with access control security. Nell'esempio viene utilizzato OpenExisting(String) l'overload del metodo per verificare l'esistenza di un mutex denominato.The example uses the OpenExisting(String) method overload to test for the existence of a named mutex.

Se il mutex non esiste, viene creato con proprietà iniziale e sicurezza del controllo di accesso che nega all'utente corrente il diritto di usare mutex, ma concede il diritto di leggere e modificare le autorizzazioni sul mutex.If the mutex does not exist, it is created with initial ownership and access control security that denies the current user the right to use the mutex, but grants the right to read and change permissions on the mutex.

Se si esegue l'esempio compilato da due finestre di comando, la seconda copia genererà un'eccezione di violazione di accesso nella OpenExisting(String)chiamata a.If you run the compiled example from two command windows, the second copy will throw an access violation exception on the call to OpenExisting(String). L'eccezione viene rilevata e nell'esempio viene OpenExisting(String, MutexRights) utilizzato l'overload del metodo per aprire il mutex con i diritti necessari per leggere e modificare le autorizzazioni.The exception is caught, and the example uses the OpenExisting(String, MutexRights) method overload to open the mutex with the rights needed to read and change the permissions.

Una volta modificate le autorizzazioni, il mutex viene aperto con i diritti necessari per l'immissione e il rilascio.After the permissions are changed, the mutex is opened with the rights required to enter and release it. Se si esegue l'esempio compilato da una terza finestra di comando, questa viene eseguita utilizzando le nuove autorizzazioni.If you run the compiled example from a third command window, it runs using the new permissions.

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

public ref class Example
{
public:
   [SecurityPermissionAttribute(SecurityAction::Demand,Flags=SecurityPermissionFlag::UnmanagedCode)]
   static void Main()
   {
      String^ 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;
            MutexSecurity 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

Se name initiallyOwned non createdNew true è e ètrue, il thread chiamante è proprietario del mutex denominato solo se si trova dopo la chiamata a. nullIf name is not null and initiallyOwned is true, the calling thread owns the named mutex only if createdNew is true after the call. In caso contrario, il thread può richiedere il mutex WaitOne chiamando il metodo.Otherwise the thread can request the mutex by calling the WaitOne method.

Utilizzare questo costruttore per applicare la sicurezza del controllo di accesso a un mutex di sistema denominato quando viene creato, impedendo ad altro codice di assumere il controllo del mutex.Use this constructor to apply access control security to a named system mutex when it is created, preventing other code from taking control of the mutex.

Questo costruttore inizializza un Mutex oggetto che rappresenta un mutex di sistema denominato.This constructor initializes a Mutex object that represents a named system mutex. È possibile creare più Mutex oggetti che rappresentano lo stesso mutex di sistema denominato.You can create multiple Mutex objects that represent the same named system mutex.

Se il mutex di sistema denominato non esiste, viene creato con la sicurezza del controllo di accesso specificata.If the named system mutex does not exist, it is created with the specified access control security. Se il mutex denominato esiste, la sicurezza del controllo di accesso specificata viene ignorata.If the named mutex exists, the specified access control security is ignored.

Nota

Il chiamante ha il controllo completo sull'oggetto appena Mutex creato anche se mutexSecurity nega o non riesce a concedere alcuni diritti di accesso all'utente corrente.The caller has full control over the newly created Mutex object even if mutexSecurity denies or fails to grant some access rights to the current user. Tuttavia, se l'utente corrente tenta di ottenere un Mutex altro oggetto per rappresentare lo stesso mutex denominato, usando un costruttore o il OpenExisting metodo, viene applicata la sicurezza del controllo di accesso di Windows.However, if the current user attempts to get another Mutex object to represent the same named mutex, using either a constructor or the OpenExisting method, Windows access control security is applied.

Se il mutex denominato è già stato creato con la sicurezza del controllo di accesso e il chiamante non MutexRights.FullControldispone di, viene generata un'eccezione.If the named mutex has already been created with access control security, and the caller does not have MutexRights.FullControl, an exception is thrown. Per aprire un mutex denominato esistente con solo le autorizzazioni necessarie per la sincronizzazione delle attività dei thread, OpenExisting vedere il metodo.To open an existing named mutex with only those permissions needed for synchronizing thread activities, see the OpenExisting method.

Se si specifica null o una stringa vuota per name, viene creato un mutex locale, come se fosse stato chiamato il Mutex(Boolean) costruttore.If you specify null or an empty string for name, a local mutex is created, as if you had called the Mutex(Boolean) constructor. In questo caso, createdNew è sempre true.In this case, createdNew is always true.

Poiché sono a livello di sistema, i mutex denominati possono essere usati per coordinare l'uso delle risorse tra i limiti dei processi.Because they are system-wide, named mutexes can be used to coordinate resource use across process boundaries.

Nota

In un server che esegue Servizi terminal, un mutex di sistema denominato può avere due livelli di visibilità.On a server that is running Terminal Services, a named system mutex can have two levels of visibility. Se il nome inizia con il prefisso "globale\", il mutex è visibile in tutte le sessioni di Terminal Server.If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. Se il nome inizia con il prefisso "Local\", il mutex è visibile solo nella sessione di Terminal Server in cui è stato creato.If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created. In tal caso, è possibile che esista un mutex separato con lo stesso nome in ogni altra sessione di Terminal Server sul server.In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server. Se non si specifica un prefisso quando si crea un mutex denominato, prende il prefisso "Local\".If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\". All'interno di una sessione di Terminal Server, due mutex i cui nomi differiscono solo per i rispettivi prefissi sono mutex distinti ed entrambi sono visibili a tutti i processi nella sessione Terminal Server.Within a terminal server session, two mutexes whose names differ only by their prefixes are separate mutexes, and both are visible to all processes in the terminal server session. Ovvero i nomi di prefisso "Global\" e "Local\" descrivono l'ambito del nome mutex rispetto alle sessioni di Terminal Server, non rispetto ai processi.That is, the prefix names "Global\" and "Local\" describe the scope of the mutex name relative to terminal server sessions, not relative to processes.

La barra rovesciata (\) è un carattere riservato in un nome di mutex.The backslash (\) is a reserved character in a mutex name. Non usare una barra rovesciata (\) in un nome del mutex, se non come specificato nella nota sull'uso dei mutex nelle sessioni di Terminal Server.Don't use a backslash (\) in a mutex name except as specified in the note on using mutexes in terminal server sessions. In caso contrario, potrebbe essere generata una DirectoryNotFoundException, anche se il nome del mutex rappresenta un file esistente.Otherwise, a DirectoryNotFoundException may be thrown, even though the name of the mutex represents an existing file.

Sicurezza

SecurityCriticalAttribute
richiede l'attendibilità totale per il chiamante immediato.Requires full trust for the immediate caller. Questo membro non può essere utilizzato da codice parzialmente attendibile o trasparente.This member cannot be used by partially trusted or transparent code.

Si applica a