Mutex.OpenExisting 方法

定義

若已存在,則開啟指定的互斥組。

多載

名稱 Description
OpenExisting(String)

若已存在,則開啟指定的命名互斥組。

OpenExisting(String, MutexRights)

若已存在,則開啟指定的互斥系統,並取得所需的安全存取權限。

OpenExisting(String, NamedWaitHandleOptions)

若已存在,則開啟指定的命名互斥組。 若選項僅設定為目前使用者,物件的存取控制會被驗證為呼叫使用者。

OpenExisting(String)

來源:
Mutex.cs
來源:
Mutex.cs
來源:
Mutex.cs
來源:
Mutex.cs
來源:
Mutex.cs

若已存在,則開啟指定的命名互斥組。

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

參數

name
String

同步物件名稱,將與其他程序共享。 名稱是區分大小寫的。 反斜線字元(\)是保留的,只能用來指定命名空間。 欲了解更多命名空間資訊,請參閱備註區。 根據作業系統不同,名稱可能有進一步限制。 例如,在基於 Unix 的作業系統中,排除命名空間後的名稱必須是有效的檔名。

傳回

一個代表命名系統互斥組的物件。

屬性

例外狀況

name 是空字串。

-或-

僅限 Framework .NET:name 超過 MAX_PATH(260 個字元)。

namenull

無法建立與所提供的 name 同步物件。 不同類型的同步物件可能名稱相同。 在某些情況下,對於無效名稱,此例外可能會被拋出。

name 無效。 這可能有各種原因,包括作業系統可能施加的一些限制,例如未知的前綴或無效字元。 請注意,名稱及常見前綴「Global\」與「Local\」皆為大小寫區分。

-或-

還有其他錯誤。 房產 HResult 可能會提供更多資訊。

Windows 僅有:name 指定了一個未知命名空間。 更多資訊請參閱 物件名稱

name太長了。 長度限制可能依作業系統或設定而異。

命名的互斥系統存在,但使用者沒有使用它所需的安全權限。

範例

以下程式碼範例展示了具存取控制安全性的命名互斥架的跨程序行為。 範例使用 OpenExisting(String) 方法過載來測試是否存在命名的互斥體。

如果 mutex 不存在,則會建立初始擁有權與存取控制安全,剝奪現有使用者使用 mutex 的權利,但允許讀取及更改 mutex 權限。

如果你從兩個指令視窗執行編譯後的範例,第二個副本會在呼叫 的 OpenExisting(String)時拋出存取違規異常。 例外被捕捉,範例利用 OpenExisting(String, MutexRights) 方法過載開啟帶有讀取與變更權限的靜音子。

權限變更後,會開啟互斥系統,並取得進入與釋放所需的權限。 如果你從第三個指令視窗執行編譯後的範例,它會使用新的權限執行。

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

備註

可以name以 或 Global\ 作為前綴Local\,以指定命名空間。 當 Global 命名空間被指定時,同步物件可以與系統上的任何程序共享。 當 Local 指定命名空間時(這也是未指定命名空間時的預設),同步物件可能會與同一會話中的程序共享。 在 Windows 上,會話是登入會話,服務通常在不同的非互動會話中執行。 在類 Unix 作業系統中,每個 shell 都有自己的會話。 會話本地同步物件可能適合在具有父/子關係且所有程序都在同一會話中執行的程序間同步。 欲了解更多關於Windows同步物件名稱的資訊,請參見 Object Names

如果命名空間中存在該請求類型的同步物件,則會開啟該現有的同步物件。 若命名空間中不存在同步物件,或命名空間中存在不同類型的同步物件,則拋出 a WaitHandleCannotBeOpenedException

OpenExisting 方法嘗試開啟指定的系統互斥。 若要建立系統互斥,當系統尚未存在時,請使用 Mutex 帶有 name 參數的建構子之一。

多次呼叫此方法且使用相同值 name ,不一定回傳相同的 Mutex 物件,即使回傳的物件代表相同的系統互斥。

此方法過載等同於呼叫 OpenExisting(String, MutexRights) 方法過載並指定 MutexRights.SynchronizeMutexRights.Modify 權利,並結合位元順序 OR 操作。

指定 MutexRights.Synchronize 標誌允許執行緒在互斥系統上等待,指定 MutexRights.Modify 標誌則允許執行緒呼叫該 ReleaseMutex 方法。

此方法不會要求擁有互斥體的所有權。

適用於

OpenExisting(String, MutexRights)

若已存在,則開啟指定的互斥系統,並取得所需的安全存取權限。

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

參數

name
String

同步物件名稱,將與其他程序共享。 名稱是區分大小寫的。 反斜線字元(\)是保留的,只能用來指定命名空間。 欲了解更多命名空間資訊,請參閱備註區。 根據作業系統不同,名稱可能有進一步限制。 例如,在基於 Unix 的作業系統中,排除命名空間後的名稱必須是有效的檔名。

rights
MutexRights

代表所需安全存取的列舉值的位元組合。

傳回

一個代表命名系統互斥組的物件。

屬性

例外狀況

name 是空字串。

-或-

僅限 Framework .NET:name 超過 MAX_PATH(260 個字元)。

namenull

無法建立與所提供的 name 同步物件。 不同類型的同步物件可能名稱相同。 在某些情況下,對於無效名稱,此例外可能會被拋出。

name 無效。 這可能有各種原因,包括作業系統可能施加的一些限制,例如未知的前綴或無效字元。 請注意,名稱及常見前綴「Global\」與「Local\」皆為大小寫區分。

-或-

還有其他錯誤。 房產 HResult 可能會提供更多資訊。

Windows 僅有:name 指定了一個未知命名空間。 更多資訊請參閱 物件名稱

name太長了。 長度限制可能依作業系統或設定而異。

雖然有命名的互斥體,但使用者沒有所需的安全存取權限。

範例

以下程式碼範例展示了具存取控制安全性的命名互斥架的跨程序行為。 範例使用 OpenExisting(String) 方法過載來測試是否存在命名的互斥體。

如果 mutex 不存在,則會建立初始擁有權與存取控制安全,剝奪現有使用者使用 mutex 的權利,但允許讀取及更改 mutex 權限。

如果你從兩個指令視窗執行編譯後的範例,第二個副本會在呼叫 的 OpenExisting(String)時拋出存取違規異常。 例外被捕捉,範例利用 OpenExisting(String, MutexRights) 方法過載開啟帶有讀取與變更權限的靜音子。

權限變更後,會開啟互斥系統,並取得進入與釋放所需的權限。 如果你從第三個指令視窗執行編譯後的範例,它會使用新的權限執行。

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

備註

可以name以 或 Global\ 作為前綴Local\,以指定命名空間。 當 Global 命名空間被指定時,同步物件可以與系統上的任何程序共享。 當 Local 指定命名空間時(這也是未指定命名空間時的預設),同步物件可能會與同一會話中的程序共享。 在 Windows 上,會話是登入會話,服務通常在不同的非互動會話中執行。 在類 Unix 作業系統中,每個 shell 都有自己的會話。 會話本地同步物件可能適合在具有父/子關係且所有程序都在同一會話中執行的程序間同步。 欲了解更多關於Windows同步物件名稱的資訊,請參見 Object Names

如果命名空間中存在該請求類型的同步物件,則會開啟該現有的同步物件。 若命名空間中不存在同步物件,或命名空間中存在不同類型的同步物件,則拋出 a WaitHandleCannotBeOpenedException

rights參數必須包含MutexRights.Synchronize允許執行緒在互斥系統等待的旗標,以及MutexRights.Modify允許執行緒呼叫該ReleaseMutex方法的旗標。

OpenExisting 方法嘗試開啟一個已存在的互斥式。 若要建立系統互斥,當系統尚未存在時,請使用 Mutex 帶有 name 參數的建構子之一。

多次呼叫此方法且使用相同值 name ,不一定回傳相同的 Mutex 物件,即使回傳的物件代表相同的系統互斥。

此方法不會要求擁有互斥體的所有權。

適用於

OpenExisting(String, NamedWaitHandleOptions)

來源:
Mutex.cs
來源:
Mutex.cs

若已存在,則開啟指定的命名互斥組。 若選項僅設定為目前使用者,物件的存取控制會被驗證為呼叫使用者。

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

參數

name
String

同步物件名稱,將與其他程序共享。 名稱是區分大小寫的。

options
NamedWaitHandleOptions

命名系統互斥的範圍選項。 預設權限僅限於目前使用者和當前會話。 指定的選項可能會影響名稱的命名空間以及對底層系統互斥物件的存取。

傳回

一個代表命名系統互斥組的物件。

例外狀況

name 是空字串。

namenull

無法建立與所提供的 name 同步物件。 不同類型的同步物件可能名稱相同。 在某些情況下,對於無效名稱,此例外可能會被拋出。

-或-

存在具有指定 name 條件的物件,但指定的 options 物件與現有物件的選項不相容。

name 無效。 這可能有各種原因,包括作業系統可能施加的一些限制,例如未知的前綴或無效字元。 請注意,名稱及常見前綴「Global\」與「Local\」皆為大小寫區分。

-或-

還有其他錯誤。 房產 HResult 可能會提供更多資訊。

Windows 僅有:name 指定了一個未知命名空間。 更多資訊請參閱 物件名稱

name太長了。 長度限制可能依作業系統或設定而異。

命名的互斥系統存在,但使用者沒有使用它所需的安全權限。

備註

如果命名空間中存在該請求類型的同步物件,則會開啟該現有的同步物件。 然而,若 options 指定存取權限僅限於目前使用者,且同步物件與其不相容,則會拋出 a WaitHandleCannotBeOpenedException 。 如果命名空間中不存在同步物件,或命名空間中存在不同類型的同步物件,則也會拋出 a WaitHandleCannotBeOpenedException

OpenExisting 方法嘗試開啟指定的系統互斥。 若要建立系統互斥,當系統尚未存在時,請使用 Mutex 帶有 name 參數的建構子之一。

多次呼叫此方法且使用相同值 name ,不一定回傳相同的 Mutex 物件,即使回傳的物件代表相同的系統互斥。

此方法不會要求擁有互斥體的所有權。

適用於