Mutex Constructeurs

Définition

Initialise une nouvelle instance de la classe Mutex.Initializes a new instance of the Mutex class.

Surcharges

Mutex()

Initialise une nouvelle instance de la classe Mutex avec des propriétés par défaut.Initializes a new instance of the Mutex class with default properties.

Mutex(Boolean)

Initialise une nouvelle instance de la classe Mutex avec une valeur booléenne qui indique si le thread appelant doit avoir la propriété initiale du 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)

Initialise une nouvelle instance de la classe Mutex avec une valeur booléenne qui indique si le thread appelant doit avoir la propriété initiale du mutex, et une chaîne représentant le nom du 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)

Initialise une nouvelle instance de la classe Mutex avec une valeur booléenne qui indique si le thread appelant doit avoir la propriété initiale du mutex, une chaîne qui représente le nom du mutex et une valeur booléenne qui, quand la méthode retourne son résultat, indique si la propriété initiale du mutex a été accordée au thread appelant.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)

Initialise une nouvelle instance de la classe Mutex avec une valeur booléenne qui indique si le thread appelant doit avoir la propriété initiale du mutex, une chaîne qui représente le nom du mutex et une variable booléenne qui, quand la méthode retourne son résultat, indique si la propriété initiale du mutex a été accordée au thread appelant, ainsi que la sécurité de contrôle d'accès à appliquer au mutex nommé.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()

Initialise une nouvelle instance de la classe Mutex avec des propriétés par défaut.Initializes a new instance of the Mutex class with default properties.

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

Exemples

L’exemple de code suivant montre comment un objet Mutex local est utilisé pour synchroniser l’accès à une ressource protégée.The following code example shows how a local Mutex object is used to synchronize access to a protected resource. Le thread qui crée le mutex ne le possède pas initialement.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

Remarques

L’appel de cette surcharge de constructeur est identique à l’appel de la surcharge du constructeur Mutex(Boolean) et à la spécification de false pour la propriété initiale du mutex.Calling this constructor overload is the same as calling the Mutex(Boolean) constructor overload and specifying false for initial ownership of the mutex. Autrement dit, le thread appelant ne possède pas le mutex.That is, the calling thread does not own the mutex.

Voir aussi

Mutex(Boolean)

Initialise une nouvelle instance de la classe Mutex avec une valeur booléenne qui indique si le thread appelant doit avoir la propriété initiale du 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)

Paramètres

initiallyOwned
Boolean

true pour accorder au thread appelant la propriété initiale du mutex ; sinon, false.true to give the calling thread initial ownership of the mutex; otherwise, false.

Exemples

L’exemple de code suivant montre comment un objet Mutex local est utilisé pour synchroniser l’accès à une ressource protégée.The following code example shows how a local Mutex object is used to synchronize access to a protected resource. Le thread qui crée le Mutex le possède initialement.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

Voir aussi

Mutex(Boolean, String)

Initialise une nouvelle instance de la classe Mutex avec une valeur booléenne qui indique si le thread appelant doit avoir la propriété initiale du mutex, et une chaîne représentant le nom du 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)

Paramètres

initiallyOwned
Boolean

true pour donner au thread appelant la propriété initiale du mutex système nommé si celui-ci est créé en réponse à cet appel ; sinon, 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

Nom du Mutex.The name of the Mutex. Si cette valeur est null, Mutex est sans nom.If the value is null, the Mutex is unnamed.

Attributs

Exceptions

Le mutex nommé existe et a la sécurité de contrôle d’accès, mais l’utilisateur n’a pas FullControl.The named mutex exists and has access control security, but the user does not have FullControl.

Une erreur Win32 s’est produite.A Win32 error occurred.

Le mutex nommé ne peut pas être créé. Il existe peut-être un handle d’attente d’un type différent portant le même nom.The named mutex cannot be created, perhaps because a wait handle of a different type has the same name.

name fait plus de 260 caractères.name is longer than 260 characters.

Exemples

L’exemple suivant montre comment un mutex nommé est utilisé pour signaler des threads qui s’exécutent dans deux processus distincts.The following example shows how a named mutex is used to signal between threads running in two separate processes.

Exécutez ce programme à partir de deux fenêtres de commande ou plus.Run this program from two or more command windows. Chaque processus crée un objet Mutex qui représente le mutex nommé MyMutex.Each process creates a Mutex object that represents the named mutex MyMutex. Le mutex nommé est un objet système dont la durée de vie est limitée par les durées de vie des objets Mutex qui le représentent.The named mutex is a system object whose lifetime is bounded by the lifetimes of the Mutex objects that represent it. Le mutex nommé est créé lorsque le premier processus crée son objet Mutex ; dans cet exemple, le mutex nommé appartient au premier processus qui exécute le programme.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. Le mutex nommé est détruit lorsque tous les objets Mutex qui le représentent ont été libérés.The named mutex is destroyed when all the Mutex objects that represent it have been released.

La surcharge de constructeur utilisée dans cet exemple ne peut pas indiquer au thread appelant si la propriété initiale du mutex nommé a été accordée.The constructor overload used in this example cannot tell the calling thread whether initial ownership of the named mutex was granted. Vous ne devez pas utiliser ce constructeur pour demander la propriété initiale, sauf si vous pouvez être certain que le thread va créer le mutex nommé.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 

Remarques

Si name n’est pas null et initiallyOwned est true, le thread appelant possède le mutex uniquement si le mutex système nommé a été créé à la suite de cet appel.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. Étant donné qu’il n’existe aucun mécanisme permettant de déterminer si le mutex système nommé a été créé, il est préférable de spécifier false pour initiallyOwned lors de l’appel de cette surcharge de constructeur.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. Vous pouvez utiliser le constructeur Mutex(Boolean, String, Boolean) si vous devez déterminer la propriété initiale.You can use the Mutex(Boolean, String, Boolean) constructor if you need to determine initial ownership.

Ce constructeur initialise un objet Mutex qui représente un mutex système nommé.This constructor initializes a Mutex object that represents a named system mutex. Vous pouvez créer plusieurs objets Mutex qui représentent le même mutex système nommé.You can create multiple Mutex objects that represent the same named system mutex.

Si le mutex nommé a déjà été créé avec la sécurité de contrôle d’accès et que l’appelant n’a pas de MutexRights.FullControl, une exception est levée.If the named mutex has already been created with access control security, and the caller does not have MutexRights.FullControl, an exception is thrown. Pour ouvrir un mutex nommé existant avec uniquement les autorisations nécessaires à la synchronisation des activités de thread, consultez la méthode OpenExisting.To open an existing named mutex with only those permissions needed for synchronizing thread activities, see the OpenExisting method.

Si vous spécifiez null ou une chaîne vide pour name, un mutex local est créé, comme si vous aviez appelé le constructeur Mutex(Boolean).If you specify null or an empty string for name, a local mutex is created, as if you had called the Mutex(Boolean) constructor. Dans ce cas, createdNew est toujours true.In this case, createdNew is always true.

Étant donné qu’ils sont à l’échelle du système, les mutex nommés peuvent être utilisés pour coordonner l’utilisation des ressources au-delà des limites du processus.Because they are system-wide, named mutexes can be used to coordinate resource use across process boundaries.

Notes

Sur un serveur qui exécute les services Terminal Server, un mutex système nommé peut avoir deux niveaux de visibilité.On a server that is running Terminal Services, a named system mutex can have two levels of visibility. Si son nom commence par le préfixe « global\», le mutex est visible dans toutes les sessions Terminal Server.If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. Si son nom commence par le préfixe « local\», le mutex est visible uniquement dans la session Terminal Server dans laquelle il a été créé.If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created. Dans ce cas, un mutex distinct du même nom peut exister dans chacune des autres sessions Terminal Server sur le serveur.In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server. Si vous ne spécifiez pas de préfixe lorsque vous créez un mutex nommé, il prend le préfixe « local\».If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\". Dans une session Terminal Server, deux mutex dont les noms diffèrent uniquement par leurs préfixes sont des mutex distincts, et les deux sont visibles par tous les processus de la session 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. Autrement dit, les noms de préfixe « global\» et « local\» décrivent l’étendue du nom de mutex par rapport aux sessions Terminal Server, et non par rapport aux processus.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 barre oblique inverse (\) est un caractère réservé dans un nom de mutex.The backslash (\) is a reserved character in a mutex name. N’utilisez pas de barre oblique inverse (\) dans un nom de mutex, sauf si spécifié dans la remarque sur l’utilisation de mutex dans les sessions Terminal Server.Don't use a backslash (\) in a mutex name except as specified in the note on using mutexes in terminal server sessions. Sinon, une DirectoryNotFoundException peut être levée, même si le nom du mutex représente un fichier existant.Otherwise, a DirectoryNotFoundException may be thrown, even though the name of the mutex represents an existing file.

Sécurité

SecurityCriticalAttribute
requiert une confiance totale pour l’appelant immédiat.Requires full trust for the immediate caller. Ce membre ne peut pas être utilisé par du code de confiance partielle ou transparent.This member cannot be used by partially trusted or transparent code.

Voir aussi

Mutex(Boolean, String, Boolean)

Initialise une nouvelle instance de la classe Mutex avec une valeur booléenne qui indique si le thread appelant doit avoir la propriété initiale du mutex, une chaîne qui représente le nom du mutex et une valeur booléenne qui, quand la méthode retourne son résultat, indique si la propriété initiale du mutex a été accordée au thread appelant.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)

Paramètres

initiallyOwned
Boolean

true pour donner au thread appelant la propriété initiale du mutex système nommé si celui-ci est créé en réponse à cet appel ; sinon, 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

Nom du Mutex.The name of the Mutex. Si cette valeur est null, Mutex est sans nom.If the value is null, the Mutex is unnamed.

createdNew
Boolean

Cette méthode retourne une valeur booléenne qui est true si un mutex local a été créé (en d'autres termes, si name est null ou une chaîne vide) ou si le mutex système nommé spécifié a été créé ; false si le mutex système nommé spécifié existait déjà.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. Ce paramètre est passé sans être initialisé.This parameter is passed uninitialized.

Attributs

Exceptions

Le mutex nommé existe et a la sécurité de contrôle d’accès, mais l’utilisateur n’a pas FullControl.The named mutex exists and has access control security, but the user does not have FullControl.

Une erreur Win32 s’est produite.A Win32 error occurred.

Le mutex nommé ne peut pas être créé. Il existe peut-être un handle d’attente d’un type différent portant le même nom.The named mutex cannot be created, perhaps because a wait handle of a different type has the same name.

name fait plus de 260 caractères.name is longer than 260 characters.

Exemples

L’exemple de code suivant montre comment un mutex nommé est utilisé pour signaler entre des processus ou des threads.The following code example shows how a named mutex is used to signal between processes or threads. Exécutez ce programme à partir de deux fenêtres de commande ou plus.Run this program from two or more command windows. Chaque processus crée un objet Mutex qui représente le mutex nommé « MyMutex ».Each process creates a Mutex object that represents the named mutex "MyMutex". Le mutex nommé est un objet système.The named mutex is a system object. Dans cet exemple, sa durée de vie est limitée par les durées de vie des objets Mutex qui le représentent.In this example, its lifetime is bounded by the lifetimes of the Mutex objects that represent it. Le mutex nommé est créé lorsque le premier processus crée son objet de Mutex local et détruit lorsque tous les objets Mutex qui le représentent ont été libérés.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. Le mutex nommé appartient initialement au premier processus.The named mutex is initially owned by the first process. Le deuxième processus et les processus suivants attendent que les processus précédents libèrent le mutex nommé.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

Remarques

Si name n’est pas null et initiallyOwned est true, le thread appelant possède le mutex nommé uniquement si createdNew est true après l’appel.If name is not null and initiallyOwned is true, the calling thread owns the named mutex only if createdNew is true after the call. Dans le cas contraire, le thread peut demander le mutex en appelant la méthode WaitOne.Otherwise the thread can request the mutex by calling the WaitOne method.

Ce constructeur initialise un objet Mutex qui représente un mutex système nommé.This constructor initializes a Mutex object that represents a named system mutex. Vous pouvez créer plusieurs objets Mutex qui représentent le même mutex système nommé.You can create multiple Mutex objects that represent the same named system mutex.

Si le mutex nommé a déjà été créé avec la sécurité de contrôle d’accès et que l’appelant n’a pas de droits de MutexRights.FullControl, une exception est levée.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. Pour ouvrir un mutex nommé existant avec uniquement les autorisations nécessaires à la synchronisation des activités de thread, consultez la méthode OpenExisting.To open an existing named mutex with only those permissions needed for synchronizing thread activities, see the OpenExisting method.

Si vous spécifiez null ou une chaîne vide pour name, un mutex local est créé, comme si vous aviez appelé le constructeur Mutex(Boolean).If you specify null or an empty string for name, a local mutex is created, as if you had called the Mutex(Boolean) constructor. Dans ce cas, createdNew est toujours true.In this case, createdNew is always true.

Étant donné qu’ils sont à l’échelle du système, les mutex nommés peuvent être utilisés pour coordonner l’utilisation des ressources au-delà des limites du processus.Because they are system-wide, named mutexes can be used to coordinate resource use across process boundaries.

Notes

Sur un serveur qui exécute les services Terminal Server, un mutex système nommé peut avoir deux niveaux de visibilité.On a server that is running Terminal Services, a named system mutex can have two levels of visibility. Si son nom commence par le préfixe « global\», le mutex est visible dans toutes les sessions Terminal Server.If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. Si son nom commence par le préfixe « local\», le mutex est visible uniquement dans la session Terminal Server dans laquelle il a été créé.If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created. Dans ce cas, un mutex distinct du même nom peut exister dans chacune des autres sessions Terminal Server sur le serveur.In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server. Si vous ne spécifiez pas de préfixe lorsque vous créez un mutex nommé, il prend le préfixe « local\».If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\". Dans une session Terminal Server, deux mutex dont les noms diffèrent uniquement par leurs préfixes sont des mutex distincts, et les deux sont visibles par tous les processus de la session 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. Autrement dit, les noms de préfixe « global\» et « local\» décrivent l’étendue du nom de mutex par rapport aux sessions Terminal Server, et non par rapport aux processus.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 barre oblique inverse (\) est un caractère réservé dans un nom de mutex.The backslash (\) is a reserved character in a mutex name. N’utilisez pas de barre oblique inverse (\) dans un nom de mutex, sauf si spécifié dans la remarque sur l’utilisation de mutex dans les sessions Terminal Server.Don't use a backslash (\) in a mutex name except as specified in the note on using mutexes in terminal server sessions. Sinon, une DirectoryNotFoundException peut être levée, même si le nom du mutex représente un fichier existant.Otherwise, a DirectoryNotFoundException may be thrown, even though the name of the mutex represents an existing file.

Sécurité

SecurityCriticalAttribute
requiert une confiance totale pour l’appelant immédiat.Requires full trust for the immediate caller. Ce membre ne peut pas être utilisé par du code de confiance partielle ou transparent.This member cannot be used by partially trusted or transparent code.

Voir aussi

Mutex(Boolean, String, Boolean, MutexSecurity)

Initialise une nouvelle instance de la classe Mutex avec une valeur booléenne qui indique si le thread appelant doit avoir la propriété initiale du mutex, une chaîne qui représente le nom du mutex et une variable booléenne qui, quand la méthode retourne son résultat, indique si la propriété initiale du mutex a été accordée au thread appelant, ainsi que la sécurité de contrôle d'accès à appliquer au mutex nommé.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

Paramètres

initiallyOwned
Boolean

true pour donner au thread appelant la propriété initiale du mutex système nommé si celui-ci est créé en réponse à cet appel ; sinon, 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

Nom du mutex système.The name of the system mutex. Si cette valeur est null, Mutex est sans nom.If the value is null, the Mutex is unnamed.

createdNew
Boolean

Cette méthode retourne une valeur booléenne qui est true si un mutex local a été créé (en d'autres termes, si name est null ou une chaîne vide) ou si le mutex système nommé spécifié a été créé ; false si le mutex système nommé spécifié existait déjà.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. Ce paramètre est passé sans être initialisé.This parameter is passed uninitialized.

mutexSecurity
MutexSecurity

Objet MutexSecurity qui représente la sécurité du contrôle d'accès à appliquer au mutex système nommé.A MutexSecurity object that represents the access control security to be applied to the named system mutex.

Attributs

Exceptions

Une erreur Win32 s’est produite.A Win32 error occurred.

Le mutex nommé existe et a la sécurité de contrôle d’accès, mais l’utilisateur n’a pas FullControl.The named mutex exists and has access control security, but the user does not have FullControl.

Le mutex nommé ne peut pas être créé. Il existe peut-être un handle d’attente d’un type différent portant le même nom.The named mutex cannot be created, perhaps because a wait handle of a different type has the same name.

name fait plus de 260 caractères.name is longer than 260 characters.

Exemples

L’exemple de code suivant illustre le comportement inter-processus d’un mutex nommé avec la sécurité de contrôle d’accès.The following code example demonstrates the cross-process behavior of a named mutex with access control security. L’exemple utilise la surcharge de méthode OpenExisting(String) pour vérifier l’existence d’un mutex nommé.The example uses the OpenExisting(String) method overload to test for the existence of a named mutex.

Si le mutex n’existe pas, il est créé avec la propriété initiale et la sécurité de contrôle d’accès qui refuse à l’utilisateur actuel le droit d’utiliser le mutex, mais accorde le droit de lire et de modifier les autorisations sur le 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.

Si vous exécutez l’exemple compilé à partir de deux fenêtres de commande, la deuxième copie lèvera une exception de violation d’accès sur l’appel à OpenExisting(String).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’exception est interceptée et l’exemple utilise la surcharge de méthode OpenExisting(String, MutexRights) pour ouvrir le mutex avec les droits nécessaires à la lecture et à la modification des autorisations.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.

Une fois les autorisations modifiées, le mutex est ouvert avec les droits requis pour l’entrer et le libérer.After the permissions are changed, the mutex is opened with the rights required to enter and release it. Si vous exécutez l’exemple compilé à partir d’une troisième fenêtre de commande, il s’exécute avec les nouvelles autorisations.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 

Remarques

Si name n’est pas null et initiallyOwned est true, le thread appelant possède le mutex nommé uniquement si createdNew est true après l’appel.If name is not null and initiallyOwned is true, the calling thread owns the named mutex only if createdNew is true after the call. Dans le cas contraire, le thread peut demander le mutex en appelant la méthode WaitOne.Otherwise the thread can request the mutex by calling the WaitOne method.

Utilisez ce constructeur pour appliquer la sécurité de contrôle d’accès à un mutex système nommé lorsqu’il est créé, ce qui empêche tout autre code de contrôler le 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.

Ce constructeur initialise un objet Mutex qui représente un mutex système nommé.This constructor initializes a Mutex object that represents a named system mutex. Vous pouvez créer plusieurs objets Mutex qui représentent le même mutex système nommé.You can create multiple Mutex objects that represent the same named system mutex.

Si le mutex système nommé n’existe pas, il est créé avec la sécurité de contrôle d’accès spécifiée.If the named system mutex does not exist, it is created with the specified access control security. Si le mutex nommé existe, la sécurité de contrôle d’accès spécifiée est ignorée.If the named mutex exists, the specified access control security is ignored.

Notes

L’appelant dispose d’un contrôle total sur l’objet de Mutex nouvellement créé, même si mutexSecurity refuse ou ne parvient pas à accorder des droits d’accès à l’utilisateur actuel.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. Toutefois, si l’utilisateur actuel tente d’obtenir un autre objet Mutex pour représenter le même mutex nommé, à l’aide d’un constructeur ou de la méthode OpenExisting, la sécurité du contrôle d’accès Windows est appliquée.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.

Si le mutex nommé a déjà été créé avec la sécurité de contrôle d’accès et que l’appelant n’a pas de MutexRights.FullControl, une exception est levée.If the named mutex has already been created with access control security, and the caller does not have MutexRights.FullControl, an exception is thrown. Pour ouvrir un mutex nommé existant avec uniquement les autorisations nécessaires à la synchronisation des activités de thread, consultez la méthode OpenExisting.To open an existing named mutex with only those permissions needed for synchronizing thread activities, see the OpenExisting method.

Si vous spécifiez null ou une chaîne vide pour name, un mutex local est créé, comme si vous aviez appelé le constructeur Mutex(Boolean).If you specify null or an empty string for name, a local mutex is created, as if you had called the Mutex(Boolean) constructor. Dans ce cas, createdNew est toujours true.In this case, createdNew is always true.

Étant donné qu’ils sont à l’échelle du système, les mutex nommés peuvent être utilisés pour coordonner l’utilisation des ressources au-delà des limites du processus.Because they are system-wide, named mutexes can be used to coordinate resource use across process boundaries.

Notes

Sur un serveur qui exécute les services Terminal Server, un mutex système nommé peut avoir deux niveaux de visibilité.On a server that is running Terminal Services, a named system mutex can have two levels of visibility. Si son nom commence par le préfixe « global\», le mutex est visible dans toutes les sessions Terminal Server.If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. Si son nom commence par le préfixe « local\», le mutex est visible uniquement dans la session Terminal Server dans laquelle il a été créé.If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created. Dans ce cas, un mutex distinct du même nom peut exister dans chacune des autres sessions Terminal Server sur le serveur.In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server. Si vous ne spécifiez pas de préfixe lorsque vous créez un mutex nommé, il prend le préfixe « local\».If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\". Dans une session Terminal Server, deux mutex dont les noms diffèrent uniquement par leurs préfixes sont des mutex distincts, et les deux sont visibles par tous les processus de la session 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. Autrement dit, les noms de préfixe « global\» et « local\» décrivent l’étendue du nom de mutex par rapport aux sessions Terminal Server, et non par rapport aux processus.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 barre oblique inverse (\) est un caractère réservé dans un nom de mutex.The backslash (\) is a reserved character in a mutex name. N’utilisez pas de barre oblique inverse (\) dans un nom de mutex, sauf si spécifié dans la remarque sur l’utilisation de mutex dans les sessions Terminal Server.Don't use a backslash (\) in a mutex name except as specified in the note on using mutexes in terminal server sessions. Sinon, une DirectoryNotFoundException peut être levée, même si le nom du mutex représente un fichier existant.Otherwise, a DirectoryNotFoundException may be thrown, even though the name of the mutex represents an existing file.

Sécurité

SecurityCriticalAttribute
requiert une confiance totale pour l’appelant immédiat.Requires full trust for the immediate caller. Ce membre ne peut pas être utilisé par du code de confiance partielle ou transparent.This member cannot be used by partially trusted or transparent code.

S’applique à