Mutex.OpenExisting Yöntem

Tanım

Zaten varsa belirtilen adlı mutex'i açar.

Aşırı Yüklemeler

Name Description
OpenExisting(String)

Belirtilen adlandırılmış mutex zaten varsa açar.

OpenExisting(String, MutexRights)

Belirtilen adlı mutex'i, zaten varsa, istenen güvenlik erişimiyle açar.

OpenExisting(String, NamedWaitHandleOptions)

Belirtilen adlandırılmış mutex zaten varsa açar. Seçenekler yalnızca geçerli kullanıcıya ayarlanırsa, nesnenin erişim denetimleri çağıran kullanıcı için doğrulanır.

OpenExisting(String)

Kaynak:
Mutex.cs
Kaynak:
Mutex.cs
Kaynak:
Mutex.cs
Kaynak:
Mutex.cs
Kaynak:
Mutex.cs

Belirtilen adlandırılmış mutex zaten varsa açar.

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

Parametreler

name
String

Diğer işlemlerle paylaşılacak eşitleme nesnesinin adı. Ad büyük/küçük harfe duyarlıdır. Ters eğik çizgi karakteri (\) ayrılmıştır ve yalnızca bir ad alanı belirtmek için kullanılabilir. Ad alanları hakkında daha fazla bilgi için açıklamalar bölümüne bakın. İşletim sistemine bağlı olarak ad üzerinde başka kısıtlamalar da olabilir. Örneğin, Unix tabanlı işletim sistemlerinde, ad alanı dışlanmadan sonraki ad geçerli bir dosya adı olmalıdır.

Döndürülenler

Adlandırılmış sistem mutex'ini temsil eden bir nesne.

Öznitelikler

Özel durumlar

name boş bir dizedir.

-veya-

Yalnızca .NET Framework: name MAX_PATH'den (260 karakter) uzundur.

name, null'e eşittir.

Sağlanan name ile bir eşitleme nesnesi oluşturulamıyor. Farklı türde bir eşitleme nesnesi aynı ada sahip olabilir. Bazı durumlarda, bu özel durum geçersiz adlar için oluşturulabilir.

name geçersiz. Bu, bilinmeyen ön ek veya geçersiz karakterler gibi işletim sistemi tarafından yerleştirilebilen bazı kısıtlamalar da dahil olmak üzere çeşitli nedenlerle olabilir. Adın ve "Genel\" ve "Yerel\" ortak ön eklerinin büyük/küçük harfe duyarlı olduğunu unutmayın.

-veya-

Başka bir hata oluştu. HResult özelliği daha fazla bilgi sağlayabilir.

Yalnızca Windows: name bilinmeyen bir ad alanı belirtti. Daha fazla bilgi için bkz. Nesne Adları .

name çok uzun. Uzunluk kısıtlamaları işletim sistemine veya yapılandırmaya bağlı olabilir.

Adlandırılmış mutex var, ancak kullanıcının bunu kullanmak için gereken güvenlik erişimi yok.

Örnekler

Aşağıdaki kod örneği, erişim denetimi güvenliğine sahip adlandırılmış bir mutex'in çapraz işlem davranışını gösterir. Örnek, adlandırılmış bir mutex'in varlığını test etmek için yöntem aşırı yüklemesini kullanır OpenExisting(String) .

Mutex yoksa, geçerli kullanıcıya mutex kullanma hakkını reddeden ancak mutex üzerinde okuma ve değiştirme izinleri veren ilk sahiplik ve erişim denetimi güvenliği ile oluşturulur.

Derlenmiş örneği iki komut penceresiyle çalıştırırsanız, ikinci kopya çağrısında OpenExisting(String)bir erişim ihlali özel durumu oluşturur. Özel durum yakalanır ve örnek, izinleri okumak ve değiştirmek için gereken haklarla mutex'i açmak için yöntem aşırı yüklemesini kullanır OpenExisting(String, MutexRights) .

İzinler değiştirildikten sonra, mutex girmek ve serbest bırakmak için gereken haklarla açılır. Derlenmiş örneği üçüncü bir komut penceresinden çalıştırırsanız, yeni izinler kullanılarak çalıştırılır.

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

Açıklamalar

name bir ad alanı belirtmek için veya Global\ ön ekine Local\ sahip olabilir. Ad alanı belirtildiğinde Global , eşitleme nesnesi sistemdeki tüm işlemlerle paylaşılabilir. Local Ad alanı belirtilmediğinde de varsayılan olan ad alanı belirtildiğinde, eşitleme nesnesi aynı oturumdaki işlemlerle paylaşılabilir. Windows oturum, oturum açma oturumudur ve hizmetler genellikle etkileşimli olmayan farklı bir oturumda çalışır. Unix benzeri işletim sistemlerinde her kabuğun kendi oturumu vardır. Oturum yerel eşitleme nesneleri, tümü aynı oturumda çalıştırıldığı bir üst/alt ilişki ile işlemler arasında eşitleme için uygun olabilir. Windows eşitleme nesnesi adları hakkında daha fazla bilgi için bkz. Object Names.

İstenen türde bir eşitleme nesnesi ad alanında varsa, var olan eşitleme nesnesi açılır. Ad alanında bir eşitleme nesnesi yoksa veya ad alanında farklı türde bir eşitleme nesnesi varsa, bir WaitHandleCannotBeOpenedException oluşturulur.

yöntemi belirtilen OpenExisting adlandırılmış sistem mutex'ini açmaya çalışır. Sistem mutex'ini henüz mevcut olmadığında oluşturmak için parametresi olan Mutex oluşturuculardan name birini kullanın.

Döndürülen nesneler aynı adlandırılmış sistem mutex'ini temsil etse bile, için aynı değeri name kullanan bu yönteme yönelik birden çok çağrı mutlaka aynı nesneyi döndürmez Mutex .

Bu yöntem aşırı yüklemesi, yöntem aşırı yüklemesini OpenExisting(String, MutexRights) çağırmaya ve bit düzeyinde OR işlemi kullanılarak birleştirilen ve MutexRights.Synchronize hakları belirtmeye MutexRights.Modify eşdeğerdir.

bayrağının MutexRights.Synchronize belirtilmesi, bir iş parçacığının mutex üzerinde beklemesine ve bayrağının belirtilmesi bir iş parçacığının MutexRights.Modify yöntemini çağırmasına ReleaseMutex olanak tanır.

Bu yöntem, mutex'in sahipliğini istemez.

Şunlara uygulanır

OpenExisting(String, MutexRights)

Belirtilen adlı mutex'i, zaten varsa, istenen güvenlik erişimiyle açar.

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

Parametreler

name
String

Diğer işlemlerle paylaşılacak eşitleme nesnesinin adı. Ad büyük/küçük harfe duyarlıdır. Ters eğik çizgi karakteri (\) ayrılmıştır ve yalnızca bir ad alanı belirtmek için kullanılabilir. Ad alanları hakkında daha fazla bilgi için açıklamalar bölümüne bakın. İşletim sistemine bağlı olarak ad üzerinde başka kısıtlamalar da olabilir. Örneğin, Unix tabanlı işletim sistemlerinde, ad alanı dışlanmadan sonraki ad geçerli bir dosya adı olmalıdır.

rights
MutexRights

İstenen güvenlik erişimini temsil eden numaralandırma değerlerinin bit düzeyinde birleşimi.

Döndürülenler

Adlandırılmış sistem mutex'ini temsil eden bir nesne.

Öznitelikler

Özel durumlar

name boş bir dizedir.

-veya-

Yalnızca .NET Framework: name MAX_PATH'den (260 karakter) uzundur.

name, null'e eşittir.

Sağlanan name ile bir eşitleme nesnesi oluşturulamıyor. Farklı türde bir eşitleme nesnesi aynı ada sahip olabilir. Bazı durumlarda, bu özel durum geçersiz adlar için oluşturulabilir.

name geçersiz. Bu, bilinmeyen ön ek veya geçersiz karakterler gibi işletim sistemi tarafından yerleştirilebilen bazı kısıtlamalar da dahil olmak üzere çeşitli nedenlerle olabilir. Adın ve "Genel\" ve "Yerel\" ortak ön eklerinin büyük/küçük harfe duyarlı olduğunu unutmayın.

-veya-

Başka bir hata oluştu. HResult özelliği daha fazla bilgi sağlayabilir.

Yalnızca Windows: name bilinmeyen bir ad alanı belirtti. Daha fazla bilgi için bkz. Nesne Adları .

name çok uzun. Uzunluk kısıtlamaları işletim sistemine veya yapılandırmaya bağlı olabilir.

Adlandırılmış mutex var, ancak kullanıcının istenen güvenlik erişimi yok.

Örnekler

Aşağıdaki kod örneği, erişim denetimi güvenliğine sahip adlandırılmış bir mutex'in çapraz işlem davranışını gösterir. Örnek, adlandırılmış bir mutex'in varlığını test etmek için yöntem aşırı yüklemesini kullanır OpenExisting(String) .

Mutex yoksa, geçerli kullanıcıya mutex kullanma hakkını reddeden ancak mutex üzerinde okuma ve değiştirme izinleri veren ilk sahiplik ve erişim denetimi güvenliği ile oluşturulur.

Derlenmiş örneği iki komut penceresiyle çalıştırırsanız, ikinci kopya çağrısında OpenExisting(String)bir erişim ihlali özel durumu oluşturur. Özel durum yakalanır ve örnek, izinleri okumak ve değiştirmek için gereken haklarla mutex'i açmak için yöntem aşırı yüklemesini kullanır OpenExisting(String, MutexRights) .

İzinler değiştirildikten sonra, mutex girmek ve serbest bırakmak için gereken haklarla açılır. Derlenmiş örneği üçüncü bir komut penceresinden çalıştırırsanız, yeni izinler kullanılarak çalıştırılır.

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

Açıklamalar

name bir ad alanı belirtmek için veya Global\ ön ekine Local\ sahip olabilir. Ad alanı belirtildiğinde Global , eşitleme nesnesi sistemdeki tüm işlemlerle paylaşılabilir. Local Ad alanı belirtilmediğinde de varsayılan olan ad alanı belirtildiğinde, eşitleme nesnesi aynı oturumdaki işlemlerle paylaşılabilir. Windows oturum, oturum açma oturumudur ve hizmetler genellikle etkileşimli olmayan farklı bir oturumda çalışır. Unix benzeri işletim sistemlerinde her kabuğun kendi oturumu vardır. Oturum yerel eşitleme nesneleri, tümü aynı oturumda çalıştırıldığı bir üst/alt ilişki ile işlemler arasında eşitleme için uygun olabilir. Windows eşitleme nesnesi adları hakkında daha fazla bilgi için bkz. Object Names.

İstenen türde bir eşitleme nesnesi ad alanında varsa, var olan eşitleme nesnesi açılır. Ad alanında bir eşitleme nesnesi yoksa veya ad alanında farklı türde bir eşitleme nesnesi varsa, bir WaitHandleCannotBeOpenedException oluşturulur.

parametresi, rights iş parçacıklarının MutexRights.Synchronize mutex üzerinde beklemesine izin vermek için bayrağını ve iş parçacıklarının MutexRights.Modify yöntemini çağırmasına izin vermek için bayrağını ReleaseMutex içermelidir.

OpenExisting yöntemi var olan bir adlandırılmış mutex'i açmaya çalışır. Sistem mutex'ini henüz mevcut olmadığında oluşturmak için parametresi olan Mutex oluşturuculardan name birini kullanın.

Döndürülen nesneler aynı adlandırılmış sistem mutex'ini temsil etse bile, için aynı değeri name kullanan bu yönteme yönelik birden çok çağrı mutlaka aynı nesneyi döndürmez Mutex .

Bu yöntem, mutex'in sahipliğini istemez.

Şunlara uygulanır

OpenExisting(String, NamedWaitHandleOptions)

Kaynak:
Mutex.cs
Kaynak:
Mutex.cs

Belirtilen adlandırılmış mutex zaten varsa açar. Seçenekler yalnızca geçerli kullanıcıya ayarlanırsa, nesnenin erişim denetimleri çağıran kullanıcı için doğrulanır.

public:
 static System::Threading::Mutex ^ OpenExisting(System::String ^ name, System::Threading::NamedWaitHandleOptions options);
public static System.Threading.Mutex OpenExisting(string name, System.Threading.NamedWaitHandleOptions options);
static member OpenExisting : string * System.Threading.NamedWaitHandleOptions -> System.Threading.Mutex
Public Shared Function OpenExisting (name As String, options As NamedWaitHandleOptions) As Mutex

Parametreler

name
String

Diğer işlemlerle paylaşılacak eşitleme nesnesinin adı. Ad büyük/küçük harfe duyarlıdır.

options
NamedWaitHandleOptions

Adlandırılmış sistem mutex'i için kapsam seçenekleri. Varsayılan erişim yalnızca geçerli kullanıcı ve geçerli oturum ile sınırlıdır. Belirtilen seçenekler, adın ad alanını ve temel alınan sistem mutex nesnesine erişimi etkileyebilir.

Döndürülenler

Adlandırılmış sistem mutex'ini temsil eden bir nesne.

Özel durumlar

name boş bir dizedir.

name, null'e eşittir.

Sağlanan name ile bir eşitleme nesnesi oluşturulamıyor. Farklı türde bir eşitleme nesnesi aynı ada sahip olabilir. Bazı durumlarda, bu özel durum geçersiz adlar için oluşturulabilir.

-veya-

Belirtilene name sahip bir nesne var, ancak belirtilen options nesne var olan nesnenin seçenekleriyle uyumlu değil.

name geçersiz. Bu, bilinmeyen ön ek veya geçersiz karakterler gibi işletim sistemi tarafından yerleştirilebilen bazı kısıtlamalar da dahil olmak üzere çeşitli nedenlerle olabilir. Adın ve "Genel\" ve "Yerel\" ortak ön eklerinin büyük/küçük harfe duyarlı olduğunu unutmayın.

-veya-

Başka bir hata oluştu. HResult özelliği daha fazla bilgi sağlayabilir.

Yalnızca Windows: name bilinmeyen bir ad alanı belirtti. Daha fazla bilgi için bkz. Nesne Adları .

name çok uzun. Uzunluk kısıtlamaları işletim sistemine veya yapılandırmaya bağlı olabilir.

Adlandırılmış mutex var, ancak kullanıcının bunu kullanmak için gereken güvenlik erişimi yok.

Açıklamalar

İstenen türde bir eşitleme nesnesi ad alanında varsa, var olan eşitleme nesnesi açılır. Ancak, geçerli kullanıcıyla sınırlı erişimi belirtirse options ve eşitleme nesnesi onunla uyumlu değilse, bir WaitHandleCannotBeOpenedException oluşturulur. Ad alanında bir eşitleme nesnesi yoksa veya ad alanında farklı türde bir eşitleme nesnesi varsa, bir WaitHandleCannotBeOpenedException de oluşturulur.

yöntemi belirtilen OpenExisting adlandırılmış sistem mutex'ini açmaya çalışır. Sistem mutex'ini henüz mevcut olmadığında oluşturmak için parametresi olan Mutex oluşturuculardan name birini kullanın.

Döndürülen nesneler aynı adlandırılmış sistem mutex'ini temsil etse bile, için aynı değeri name kullanan bu yönteme yönelik birden çok çağrı mutlaka aynı nesneyi döndürmez Mutex .

Bu yöntem, mutex'in sahipliğini istemez.

Şunlara uygulanır