Mutex.OpenExisting Methode

Definition

Öffnet einen angegebenen benannten Mutex, sofern er bereits vorhanden ist.

Überlädt

Name Beschreibung
OpenExisting(String)

Öffnet den angegebenen benannten Mutex, sofern er bereits vorhanden ist.

OpenExisting(String, MutexRights)

Öffnet den angegebenen benannten Mutex, sofern er bereits vorhanden ist, mit dem gewünschten Sicherheitszugriff.

OpenExisting(String)

Öffnet den angegebenen benannten Mutex, sofern er bereits vorhanden ist.

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

Parameter

name
String

Der Name des Synchronisierungsobjekts, das für andere Prozesse freigegeben werden soll. Bei dem Namen wird die Groß-/Kleinschreibung beachtet. Das umgekehrte Schrägstrichzeichen (\) ist reserviert und kann nur verwendet werden, um einen Namespace anzugeben. Weitere Informationen zu Namespaces finden Sie im Abschnitt "Hinweise". Je nach Betriebssystem kann es weitere Einschränkungen für den Namen geben. Bei Unix-basierten Betriebssystemen muss beispielsweise der Name nach Ausschluss des Namespaces ein gültiger Dateiname sein.

Gibt zurück

Ein Objekt, das den benannten Systemmutex darstellt.

Attribute

Ausnahmen

name ist eine leere Zeichenfolge.

-oder-

.NET Framework: name ist länger als MAX_PATH (260 Zeichen).

name ist null.

Ein Synchronisierungsobjekt mit dem bereitgestellten name Objekt kann nicht erstellt werden. Ein Synchronisierungsobjekt eines anderen Typs hat möglicherweise denselben Namen. In einigen Fällen kann diese Ausnahme für ungültige Namen ausgelöst werden.

name ist ungültig. Dies kann aus verschiedenen Gründen sein, einschließlich einiger Einschränkungen, die vom Betriebssystem platziert werden können, z. B. ein unbekanntes Präfix oder ungültige Zeichen. Beachten Sie, dass bei namen und allgemeinen Präfixen "Global\" und "Local\" die Groß-/Kleinschreibung beachtet wird.

-oder-

Es gab einen anderen Fehler. Die HResult Eigenschaft kann weitere Informationen bereitstellen.

nur Windows: name einen unbekannten Namespace angegeben. Weitere Informationen finden Sie unter Objektnamen .

name ist zu lang. Längenbeschränkungen hängen möglicherweise vom Betriebssystem oder der Konfiguration ab.

Der benannte Mutex ist vorhanden, der Benutzer verfügt jedoch nicht über den sicherheitsrelevanten Zugriff, der für die Verwendung erforderlich ist.

Beispiele

Im folgenden Codebeispiel wird das prozessübergreifende Verhalten eines benannten Mutex mit Zugriffssteuerungssicherheit veranschaulicht. Im Beispiel wird die OpenExisting(String) Methodenüberladung verwendet, um das Vorhandensein eines benannten Mutex zu testen.

Wenn das Mutex nicht vorhanden ist, wird es mit der ursprünglichen Besitz- und Zugriffssteuerungssicherheit erstellt, die dem aktuellen Benutzer das Recht auf Nutzung des Mutex verweigert, gewährt aber das Recht, Berechtigungen für den Mutex zu lesen und zu ändern.

Wenn Sie das kompilierte Beispiel aus zwei Befehlsfenstern ausführen, löst die zweite Kopie eine Zugriffsverletzungs-Ausnahme für den Aufruf OpenExisting(String)aus. Die Ausnahme wird abgefangen, und im Beispiel wird die OpenExisting(String, MutexRights) Methodenüberladung verwendet, um den Mutex mit den zum Lesen und Ändern der Berechtigungen erforderlichen Rechte zu öffnen.

Nachdem die Berechtigungen geändert wurden, wird der Mutex mit den zum Eingeben und Freigeben erforderlichen Rechten geöffnet. Wenn Sie das kompilierte Beispiel aus einem dritten Befehlsfenster ausführen, wird es mit den neuen Berechtigungen ausgeführt.

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

internal class Example
{
    internal static void Main()
    {
        const string mutexName = "MutexExample4";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Friend Class Example

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

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

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

        ' Attempt to open the named mutex.
        Try
            ' Open the mutex with (MutexRights.Synchronize Or
            ' MutexRights.Modify), to enter and release the
            ' named mutex.
            '
            m = Mutex.OpenExisting(mutexName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Mutex does not exist.")
            doesNotExist = True
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", ex.Message)
            unauthorized = True
        End Try

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

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

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

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

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

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

        ElseIf unauthorized Then

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

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

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

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

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

                Console.WriteLine("Updated mutex security.")

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

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

        End If

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

        Console.WriteLine("Press the Enter key to exit.")
        Console.ReadLine()
        m.ReleaseMutex()
        m.Dispose()
    End Sub 
End Class

Hinweise

Möglicherweise name wird dem Namespace ein Präfix vorangestellt Global\ oder Local\ angegeben. Wenn der Global Namespace angegeben ist, kann das Synchronisierungsobjekt für alle Prozesse im System freigegeben werden. Wenn der Local Namespace angegeben ist, was auch der Standardwert ist, wenn kein Namespace angegeben wird, kann das Synchronisierungsobjekt für Prozesse in derselben Sitzung freigegeben werden. Bei Windows ist eine Sitzung eine Anmeldesitzung, und Dienste werden in der Regel in einer anderen nicht interaktiven Sitzung ausgeführt. Auf Unix-ähnlichen Betriebssystemen verfügt jede Shell über eine eigene Sitzung. Sitzungslokale Synchronisierungsobjekte können für die Synchronisierung zwischen Prozessen mit einer Beziehung zwischen übergeordnetem/untergeordnetem Element geeignet sein, in der sie alle in derselben Sitzung ausgeführt werden. Weitere Informationen zu Synchronisierungsobjektnamen in Windows finden Sie unter Object Names.

Wenn ein Synchronisierungsobjekt des angeforderten Typs im Namespace vorhanden ist, wird das vorhandene Synchronisierungsobjekt geöffnet. Wenn ein Synchronisierungsobjekt im Namespace nicht vorhanden ist oder ein Synchronisierungsobjekt eines anderen Typs im Namespace vorhanden ist, wird ein WaitHandleCannotBeOpenedException Fehler ausgelöst.

Die OpenExisting Methode versucht, den angegebenen benannten Systemmutex zu öffnen. Verwenden Sie einen der Konstruktoren, die Mutex über einen name Parameter verfügen, um den Systemmutex zu erstellen, wenn er noch nicht vorhanden ist.

Mehrere Aufrufe dieser Methode, für die derselbe Wert name verwendet wird, geben nicht unbedingt dasselbe Mutex Objekt zurück, obwohl die zurückgegebenen Objekte denselben benannten Systemmutex darstellen.

Diese Methodenüberladung entspricht dem Aufrufen der OpenExisting(String, MutexRights) Methodenüberladung und der Angabe MutexRights.Synchronize und MutexRights.Modify Rechte, kombiniert mit dem bitweisen OR-Vorgang.

Wenn Sie das MutexRights.Synchronize Kennzeichen angeben, kann ein Thread auf den Mutex warten und das MutexRights.Modify Flag angeben, dass ein Thread die ReleaseMutex Methode aufrufen kann.

Diese Methode fordert keinen Besitz des Mutex an.

Gilt für:

OpenExisting(String, MutexRights)

Öffnet den angegebenen benannten Mutex, sofern er bereits vorhanden ist, mit dem gewünschten Sicherheitszugriff.

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

Parameter

name
String

Der Name des Synchronisierungsobjekts, das für andere Prozesse freigegeben werden soll. Bei dem Namen wird die Groß-/Kleinschreibung beachtet. Das umgekehrte Schrägstrichzeichen (\) ist reserviert und kann nur verwendet werden, um einen Namespace anzugeben. Weitere Informationen zu Namespaces finden Sie im Abschnitt "Hinweise". Je nach Betriebssystem kann es weitere Einschränkungen für den Namen geben. Bei Unix-basierten Betriebssystemen muss beispielsweise der Name nach Ausschluss des Namespaces ein gültiger Dateiname sein.

rights
MutexRights

Eine bitweise Kombination der Enumerationswerte, die den gewünschten Sicherheitszugriff darstellen.

Gibt zurück

Ein Objekt, das den benannten Systemmutex darstellt.

Attribute

Ausnahmen

name ist eine leere Zeichenfolge.

-oder-

.NET Framework: name ist länger als MAX_PATH (260 Zeichen).

name ist null.

Ein Synchronisierungsobjekt mit dem bereitgestellten name Objekt kann nicht erstellt werden. Ein Synchronisierungsobjekt eines anderen Typs hat möglicherweise denselben Namen. In einigen Fällen kann diese Ausnahme für ungültige Namen ausgelöst werden.

name ist ungültig. Dies kann aus verschiedenen Gründen sein, einschließlich einiger Einschränkungen, die vom Betriebssystem platziert werden können, z. B. ein unbekanntes Präfix oder ungültige Zeichen. Beachten Sie, dass bei namen und allgemeinen Präfixen "Global\" und "Local\" die Groß-/Kleinschreibung beachtet wird.

-oder-

Es gab einen anderen Fehler. Die HResult Eigenschaft kann weitere Informationen bereitstellen.

nur Windows: name einen unbekannten Namespace angegeben. Weitere Informationen finden Sie unter Objektnamen .

name ist zu lang. Längenbeschränkungen hängen möglicherweise vom Betriebssystem oder der Konfiguration ab.

Der benannte Mutex ist vorhanden, der Benutzer verfügt jedoch nicht über den gewünschten Sicherheitszugriff.

Beispiele

Im folgenden Codebeispiel wird das prozessübergreifende Verhalten eines benannten Mutex mit Zugriffssteuerungssicherheit veranschaulicht. Im Beispiel wird die OpenExisting(String) Methodenüberladung verwendet, um das Vorhandensein eines benannten Mutex zu testen.

Wenn das Mutex nicht vorhanden ist, wird es mit der ursprünglichen Besitz- und Zugriffssteuerungssicherheit erstellt, die dem aktuellen Benutzer das Recht auf Nutzung des Mutex verweigert, gewährt aber das Recht, Berechtigungen für den Mutex zu lesen und zu ändern.

Wenn Sie das kompilierte Beispiel aus zwei Befehlsfenstern ausführen, löst die zweite Kopie eine Zugriffsverletzungs-Ausnahme für den Aufruf OpenExisting(String)aus. Die Ausnahme wird abgefangen, und im Beispiel wird die OpenExisting(String, MutexRights) Methodenüberladung verwendet, um den Mutex mit den zum Lesen und Ändern der Berechtigungen erforderlichen Rechte zu öffnen.

Nachdem die Berechtigungen geändert wurden, wird der Mutex mit den zum Eingeben und Freigeben erforderlichen Rechten geöffnet. Wenn Sie das kompilierte Beispiel aus einem dritten Befehlsfenster ausführen, wird es mit den neuen Berechtigungen ausgeführt.

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

internal class Example
{
    internal static void Main()
    {
        const string mutexName = "MutexExample4";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Friend Class Example

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

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

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

        ' Attempt to open the named mutex.
        Try
            ' Open the mutex with (MutexRights.Synchronize Or
            ' MutexRights.Modify), to enter and release the
            ' named mutex.
            '
            m = Mutex.OpenExisting(mutexName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Mutex does not exist.")
            doesNotExist = True
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", ex.Message)
            unauthorized = True
        End Try

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

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

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

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

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

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

        ElseIf unauthorized Then

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

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

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

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

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

                Console.WriteLine("Updated mutex security.")

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

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

        End If

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

        Console.WriteLine("Press the Enter key to exit.")
        Console.ReadLine()
        m.ReleaseMutex()
        m.Dispose()
    End Sub 
End Class

Hinweise

Möglicherweise name wird dem Namespace ein Präfix vorangestellt Global\ oder Local\ angegeben. Wenn der Global Namespace angegeben ist, kann das Synchronisierungsobjekt für alle Prozesse im System freigegeben werden. Wenn der Local Namespace angegeben ist, was auch der Standardwert ist, wenn kein Namespace angegeben wird, kann das Synchronisierungsobjekt für Prozesse in derselben Sitzung freigegeben werden. Bei Windows ist eine Sitzung eine Anmeldesitzung, und Dienste werden in der Regel in einer anderen nicht interaktiven Sitzung ausgeführt. Auf Unix-ähnlichen Betriebssystemen verfügt jede Shell über eine eigene Sitzung. Sitzungslokale Synchronisierungsobjekte können für die Synchronisierung zwischen Prozessen mit einer Beziehung zwischen übergeordnetem/untergeordnetem Element geeignet sein, in der sie alle in derselben Sitzung ausgeführt werden. Weitere Informationen zu Synchronisierungsobjektnamen in Windows finden Sie unter Object Names.

Wenn ein Synchronisierungsobjekt des angeforderten Typs im Namespace vorhanden ist, wird das vorhandene Synchronisierungsobjekt geöffnet. Wenn ein Synchronisierungsobjekt im Namespace nicht vorhanden ist oder ein Synchronisierungsobjekt eines anderen Typs im Namespace vorhanden ist, wird ein WaitHandleCannotBeOpenedException Fehler ausgelöst.

Der rights Parameter muss das MutexRights.Synchronize Flag enthalten, damit Threads auf den Mutex warten können, und das MutexRights.Modify Flag, damit Threads die ReleaseMutex Methode aufrufen können.

Die OpenExisting Methode versucht, einen vorhandenen benannten Mutex zu öffnen. Verwenden Sie einen der Konstruktoren, die Mutex über einen name Parameter verfügen, um den Systemmutex zu erstellen, wenn er noch nicht vorhanden ist.

Mehrere Aufrufe dieser Methode, für die derselbe Wert name verwendet wird, geben nicht unbedingt dasselbe Mutex Objekt zurück, obwohl die zurückgegebenen Objekte denselben benannten Systemmutex darstellen.

Diese Methode fordert keinen Besitz des Mutex an.

Gilt für: