Mutex 建構函式

定義

初始化 Mutex 類別的新執行個體。

多載

名稱 Description
Mutex()

初始化一個帶有預設屬性的新 Mutex 類別實例。

Mutex(Boolean)

初始化一個新的類別實例 Mutex ,並設定一個布林值,指示呼叫執行緒是否應該擁有該互斥體的初始擁有權。

Mutex(Boolean, String)

初始化一個新的類別實例 Mutex ,並以布林值表示呼叫執行緒是否應擁有該互斥線的初始擁有權,並初始化一個為該互斥節名稱的字串。

Mutex(String, NamedWaitHandleOptions)

初始化一個新的類別實例 Mutex ,並以一個串列為互斥體名稱,並設定使用者範圍與會話範圍存取權的選項。 呼叫執行緒不會要求擁有 mutex 的初始擁有權。

Mutex(Boolean, String, Boolean)

初始化一個新的類別實例 Mutex ,包含一個布林值,表示呼叫執行緒是否應該擁有該靜止陣的初始擁有權,一個字串即為該互斥線的名稱,以及一個布林值,當方法回傳時,表示呼叫執行緒是否獲得了該靜止陣的初始擁有權。

Mutex(Boolean, String, NamedWaitHandleOptions)

初始化一個新的類別實例 Mutex ,並以布林值表示呼叫執行緒是否應擁有 mutex 的初始擁有權、一個為 mutex 名稱的字串,以及設定使用者範圍與 session-scope 存取的選項。

Mutex(Boolean, String, Boolean, MutexSecurity)

初始化一個新的類別實例 Mutex ,包含一個布林值(表示呼叫執行緒是否應擁有該互斥線的初始擁有權)、一個為該互斥體名稱的字串、一個布林變數(當方法回傳時表示呼叫執行緒是否獲得該靜止子的初始擁有權),以及將套用於該互斥體的存取控制安全性。

Mutex(Boolean, String, NamedWaitHandleOptions, Boolean)

初始化一個新的類別實例 Mutex ,並以布林值表示呼叫執行緒是否應擁有該互斥節的初始擁有權、一個作為互斥節名稱的字串、設定使用者範圍與會話範圍存取的選項,以及一個布林值,當方法回傳時,表示呼叫執行緒是否獲得了該互斥節的初始擁有權。

Mutex()

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

初始化一個帶有預設屬性的新 Mutex 類別實例。

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

範例

以下程式碼範例說明如何利用本地 Mutex 物件同步對受保護資源的存取。 創建 mutex 的執行緒最初並不擁有該執行緒。

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

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

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

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

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

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

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

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

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

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

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

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

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

    End Sub

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

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

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

        ' Place code to access non-reentrant resources here.

        ' Simulate some work
        Thread.Sleep(500)

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

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

備註

呼叫此建構子過載等同於呼叫 Mutex(Boolean) 建構子過載並指定 false 對互斥體的初始擁有權。 也就是說,呼叫執行緒不擁有這個互斥體。

另請參閱

  • 管理的執行緒
  • Mutex

適用於

Mutex(Boolean)

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

初始化一個新的類別實例 Mutex ,並設定一個布林值,指示呼叫執行緒是否應該擁有該互斥體的初始擁有權。

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

參數

initiallyOwned
Boolean

true以賦予呼叫執行緒對互斥體的初始擁有權;否則,。 false

範例

以下程式碼範例說明如何利用本地 Mutex 物件同步對受保護資源的存取。 創建執行 Mutex 緒的執行緒最初擁有它。

using System;
using System.Threading;

class Test
{
    private static Mutex mut;
    private const int numIterations = 1;
    private const int numThreads = 3;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        ' Place code to access non-reentrant resources here.

        ' Simulate some work
        Thread.Sleep(500)

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

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

另請參閱

  • 管理的執行緒
  • Mutex

適用於

Mutex(Boolean, String)

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

初始化一個新的類別實例 Mutex ,並以布林值表示呼叫執行緒是否應擁有該互斥線的初始擁有權,並初始化一個為該互斥節名稱的字串。

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

參數

initiallyOwned
Boolean

true若命名系統互斥器是因呼叫而產生,則賦予呼叫執行緒對該系統互斥機構的初始擁有權;否則,。 false

name
String

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

屬性

例外狀況

命名的互斥機構存在且具備存取控制安全性,但使用者沒有 FullControl

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

-或-

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

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

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

無法建立與所提供的 name 同步物件。 不同類型的同步物件可能名稱相同。

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

範例

以下範例展示了命名的互斥體如何用於兩個獨立程序執行緒間的訊號。

從兩個或更多指令視窗執行這個程式。 每個程序會產生 Mutex 一個物件,代表命名的互斥體 MyMutex。 命名的互斥體是一個系統物件,其壽命受代表該物件壽命 Mutex 的限制。 命名互斥由第一個程序建立其 Mutex 物件時產生;在此範例中,命名互斥由執行該程式的第一個程序擁有。 當所有 Mutex 代表它的物件都被釋放時,命名的mutex就會被銷毀。

本範例中使用的建構子過載無法告訴呼叫執行緒是否被授予命名的靜止子初始擁有權。 除非你能確定執行緒會建立命名的 mutex,否則不應該用這個建構子來請求初始擁有權。

using System;
using System.Threading;

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

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

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

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

備註

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

如果已提供 a name ,且命名空間中已有該請求類型的同步物件,則會使用現有的同步物件。 如果命名空間中已有不同類型的同步物件,則會拋出 a WaitHandleCannotBeOpenedException 。 否則,會建立一個新的同步物件。

name 不是nullinitiallyOwned且且 ,true則呼叫執行緒只有在該系統的互斥體是因該呼叫而產生時,才擁有該互斥體。 由於無法判斷命名系統的靜止子是否被創建,因此在呼叫此建構子過載時,最好指定false為 。initiallyOwned 如果你需要確定初始所有權,可以使用建 Mutex(Boolean, String, Boolean) 構器。

此建構器初始化一個 Mutex 代表命名系統互斥的物件。 你可以建立多個 Mutex 物件,代表同一個名稱的系統互斥。

若已建立已具存取控制安全的命名互斥組,且呼叫者尚未具備 MutexRights.FullControl,則會拋出例外。 若要以僅需同步執行緒活動所需的權限開啟現有的命名互斥機構,請參見此 OpenExisting 方法。

如果你指定 null 或 一個空字串 , name會建立一個局部互斥,就像你呼叫 Mutex(Boolean) 了建構子一樣。

由於它們是系統性的,命名互斥組可用來協調跨流程邊界的資源使用。

備註

在執行終端服務的伺服器上,命名的系統mutex可以有兩層可視性。 若其名稱以前綴 Global\開頭,該互斥在所有終端伺服器會話中可見。 若其名稱以前綴 Local\開頭,該互斥僅在建立該終端伺服器會話中可見。 在這種情況下,伺服器上其他終端伺服器會話中可以存在一個同名的獨立互斥機構。 如果你在建立命名的互斥組織時未指定前綴,則會取用前綴 Local\。 在終端伺服器會話中,兩個僅以前綴名稱不同的互斥是獨立的互斥,且兩者皆對終端伺服器會話中的所有程序可見。 也就是說,前綴名稱 Global\Local\ 描述了 mutex 名稱相對於終端伺服器會話的範圍,而非相對於程序的範圍。

Caution

預設情況下,命名的互斥機構不會限制於建立它的使用者。 其他使用者可能能夠開啟並使用互斥體,包括透過進入互斥體而不退出來干擾該互斥體。 在類 Unix 作業系統中,檔案系統用於命名互斥的實作,其他使用者可能能以更重要的方式干涉命名互斥。 在Windows中,為了限制特定使用者的存取,你可以使用建構子過載(MutexAcl,並在建立命名的 mutex 時傳遞 MutexSecurity。 在類 Unix 作業系統中,目前無法限制對命名互斥的存取。 避免在可能有不受信任使用者執行程式碼的系統中使用無存取限制的命名互斥節。

反斜線(\)是變音子名稱中的保留字元。 除非在終端伺服器會話中使用互斥位的說明中另有說明,否則不要在互斥位名稱中使用反斜線(\)。 否則,即使 mutex 名稱代表已存在的檔案,也可能拋出 a DirectoryNotFoundException

另請參閱

  • 管理的執行緒
  • Mutex

適用於

Mutex(String, NamedWaitHandleOptions)

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

初始化一個新的類別實例 Mutex ,並以一個串列為互斥體名稱,並設定使用者範圍與會話範圍存取權的選項。 呼叫執行緒不會要求擁有 mutex 的初始擁有權。

public:
 Mutex(System::String ^ name, System::Threading::NamedWaitHandleOptions options);
public Mutex(string? name, System.Threading.NamedWaitHandleOptions options);
new System.Threading.Mutex : string * System.Threading.NamedWaitHandleOptions -> System.Threading.Mutex
Public Sub New (name As String, options As NamedWaitHandleOptions)

參數

name
String

若同步物件要與其他程序共享,則使用名稱;否則, null 或空字串。 名稱會區分大小寫。

options
NamedWaitHandleOptions

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

例外狀況

命名的互斥機構存在且具備存取控制安全性,但使用者沒有 FullControl

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

-或-

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

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

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

無法建立與所提供的 name 同步物件。 不同類型的同步物件可能名稱相同。 -或-

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

備註

若已提供 a name ,且命名空間中已有請求類型的同步物件,則使用現有的同步物件;但若 options 指定存取權限僅限於目前使用者且同步物件不相容,則拋出 a WaitHandleCannotBeOpenedException 。 如果命名空間中已經存在不同類型的同步物件,也會拋出 a WaitHandleCannotBeOpenedException 。 否則,會建立一個新的同步物件。

此建構器初始化一個 Mutex 代表命名系統互斥的物件。 你可以建立多個 Mutex 物件,代表同一個名稱的系統互斥。

若已建立已具存取控制安全的命名互斥組,且呼叫者尚未具備 MutexRights.FullControl,則會拋出例外。 若要以僅需同步執行緒活動所需的權限開啟現有的命名互斥機構,請參見此 OpenExisting 方法。

如果你指定 null 或 一個空字串 , name會建立一個局部互斥,就像你呼叫 Mutex(Boolean) 了建構子一樣。

由於它們是系統性的,命名互斥組可用來協調跨流程邊界的資源使用。

options參數可用來指定命名的互斥節是僅對當前使用者開放,還是所有使用者都能存取。 它也允許你指定指定的互斥區是只對當前會話中的程序可存取,還是所有會話都能存取。 如需詳細資訊,請參閱NamedWaitHandleOptions

反斜線(\)是變音子名稱中的保留字元。 除非在終端伺服器會話中使用互斥位的說明中另有說明,否則不要在互斥位名稱中使用反斜線(\)。 否則,即使 mutex 名稱代表已存在的檔案,也可能拋出 a DirectoryNotFoundException

另請參閱

  • 管理的執行緒
  • Mutex

適用於

Mutex(Boolean, String, Boolean)

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

初始化一個新的類別實例 Mutex ,包含一個布林值,表示呼叫執行緒是否應該擁有該靜止陣的初始擁有權,一個字串即為該互斥線的名稱,以及一個布林值,當方法回傳時,表示呼叫執行緒是否獲得了該靜止陣的初始擁有權。

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

參數

initiallyOwned
Boolean

true若命名系統互斥器是因呼叫而產生,則賦予呼叫執行緒對該系統互斥機構的初始擁有權;否則,。 false

name
String

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

createdNew
Boolean

當此方法回傳時,包含一個布林值,即 true 若已建立局部互斥集(即為 namenull 為空字串),或是否已建立 false 指定的系統互斥集;若指定的系統互斥候節已存在。 這個參數會未初始化傳遞。

屬性

例外狀況

命名的互斥機構存在且具備存取控制安全性,但使用者沒有 FullControl

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

-或-

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

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

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

無法建立與所提供的 name 同步物件。 不同類型的同步物件可能名稱相同。

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

範例

以下程式碼範例展示了如何利用命名的互斥體在程序或執行緒間發出訊號。 從兩個或更多指令視窗執行這個程式。 每個程序會建立 Mutex 一個物件,代表命名的 mutex 「MyMutex」。 命名的 mutex 是一個系統物件。 在此例子中,其壽命受代表其物件壽命 Mutex 的限制。 命名的 mutex 會在第一個程序建立其本地 Mutex 物件時產生,當 Mutex 所有代表它的物件都被釋放時,該互斥體會被銷毀。 命名的互斥體最初由第一個程序擁有。 第二個程序及後續程序會等待前一個程序釋放命名的互斥。

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

using System;
using System.Threading;

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

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

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

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

Imports System.Threading

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

備註

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

如果已提供 a name ,且命名空間中已有該請求類型的同步物件,則會使用現有的同步物件。 如果命名空間中已有不同類型的同步物件,則會拋出 a WaitHandleCannotBeOpenedException 。 否則,會建立一個新的同步物件。

name 不是nullinitiallyOwned且且 ,true則呼叫執行緒只有在createdNew呼叫後 才true擁有命名的互斥體。 否則執行緒可透過呼叫 WaitOne 方法請求靜止子。

此建構器初始化一個 Mutex 代表命名系統互斥的物件。 你可以建立多個 Mutex 物件,代表同一個名稱的系統互斥。

如果已建立已具備存取控制安全的命名互斥組,且呼叫者沒有 MutexRights.FullControl 權限,則會拋出例外。 若要以僅需同步執行緒活動所需的權限開啟現有的命名互斥機構,請參見此 OpenExisting 方法。

如果你指定 null 或 一個空字串 , name會建立一個局部互斥,就像你呼叫 Mutex(Boolean) 了建構子一樣。 在此情況下, createdNew 總是 true

由於它們是系統性的,命名互斥組可用來協調跨流程邊界的資源使用。

備註

在執行終端服務的伺服器上,命名的系統mutex可以有兩層可視性。 若其名稱以前綴 Global\開頭,該互斥在所有終端伺服器會話中可見。 若其名稱以前綴 Local\開頭,該互斥僅在建立該終端伺服器會話中可見。 在這種情況下,伺服器上其他終端伺服器會話中可以存在一個同名的獨立互斥機構。 如果你在建立命名的互斥組織時未指定前綴,則會取用前綴 Local\。 在終端伺服器會話中,兩個僅以前綴名稱不同的互斥是獨立的互斥,且兩者皆對終端伺服器會話中的所有程序可見。 也就是說,前綴名稱 Global\Local\ 描述了 mutex 名稱相對於終端伺服器會話的範圍,而非相對於程序的範圍。

Caution

預設情況下,命名的互斥機構不會限制於建立它的使用者。 其他使用者可能能夠開啟並使用互斥體,包括透過進入互斥體而不退出來干擾該互斥體。 在類 Unix 作業系統中,檔案系統用於命名互斥的實作,其他使用者可能能以更重要的方式干涉命名互斥。 在Windows中,為了限制特定使用者的存取,你可以使用建構子過載(MutexAcl,並在建立命名的 mutex 時傳遞 MutexSecurity。 在類 Unix 作業系統中,目前無法限制對命名互斥的存取。 避免在可能有不受信任使用者執行程式碼的系統中使用無存取限制的命名互斥節。

反斜線(\)是變音子名稱中的保留字元。 除非在終端伺服器會話中使用互斥位的說明中另有說明,否則不要在互斥位名稱中使用反斜線(\)。 否則,即使 mutex 名稱代表已存在的檔案,也可能拋出 a DirectoryNotFoundException

另請參閱

  • 管理的執行緒
  • Mutex

適用於

Mutex(Boolean, String, NamedWaitHandleOptions)

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

初始化一個新的類別實例 Mutex ,並以布林值表示呼叫執行緒是否應擁有 mutex 的初始擁有權、一個為 mutex 名稱的字串,以及設定使用者範圍與 session-scope 存取的選項。

public:
 Mutex(bool initiallyOwned, System::String ^ name, System::Threading::NamedWaitHandleOptions options);
public Mutex(bool initiallyOwned, string? name, System.Threading.NamedWaitHandleOptions options);
new System.Threading.Mutex : bool * string * System.Threading.NamedWaitHandleOptions -> System.Threading.Mutex
Public Sub New (initiallyOwned As Boolean, name As String, options As NamedWaitHandleOptions)

參數

initiallyOwned
Boolean

true若命名系統互斥器是因呼叫而產生,則賦予呼叫執行緒對該系統互斥機構的初始擁有權;否則,。 false

name
String

若同步物件要與其他程序共享,則使用名稱;否則, null 或空字串。 名稱會區分大小寫。

options
NamedWaitHandleOptions

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

例外狀況

命名的互斥機構存在且具備存取控制安全性,但使用者沒有 FullControl

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

-或-

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

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

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

無法建立與所提供的 name 同步物件。 不同類型的同步物件可能名稱相同。 -或-

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

備註

若已提供 a name ,且命名空間中已有請求類型的同步物件,則使用現有的同步物件;但若 options 指定存取權限僅限於目前使用者且同步物件不相容,則拋出 a WaitHandleCannotBeOpenedException 。 如果命名空間中已經存在不同類型的同步物件,也會拋出 a WaitHandleCannotBeOpenedException 。 否則,會建立一個新的同步物件。

name 不是nullinitiallyOwned且且 ,true則呼叫執行緒只有在該系統的互斥體是因該呼叫而產生時,才擁有該互斥體。 由於無法判斷命名系統的靜止子是否被創建,因此在呼叫此建構子過載時,最好指定false為 。initiallyOwned 如果你需要確定初始所有權,可以使用建 Mutex(Boolean, String, Boolean) 構器。

此建構器初始化一個 Mutex 代表命名系統互斥的物件。 你可以建立多個 Mutex 物件,代表同一個名稱的系統互斥。

若已建立已具存取控制安全的命名互斥組,且呼叫者尚未具備 MutexRights.FullControl,則會拋出例外。 若要以僅需同步執行緒活動所需的權限開啟現有的命名互斥機構,請參見此 OpenExisting 方法。

如果你指定 null 或 一個空字串 , name會建立一個局部互斥,就像你呼叫 Mutex(Boolean) 了建構子一樣。

由於它們是系統性的,命名互斥組可用來協調跨流程邊界的資源使用。

options參數可用來指定命名的互斥節是僅對當前使用者開放,還是所有使用者都能存取。 它也允許你指定指定的互斥區是只對當前會話中的程序可存取,還是所有會話都能存取。 如需詳細資訊,請參閱NamedWaitHandleOptions

另請參閱

  • 管理的執行緒
  • Mutex

適用於

Mutex(Boolean, String, Boolean, MutexSecurity)

初始化一個新的類別實例 Mutex ,包含一個布林值(表示呼叫執行緒是否應擁有該互斥線的初始擁有權)、一個為該互斥體名稱的字串、一個布林變數(當方法回傳時表示呼叫執行緒是否獲得該靜止子的初始擁有權),以及將套用於該互斥體的存取控制安全性。

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

參數

initiallyOwned
Boolean

true若命名系統互斥器是因呼叫而產生,則賦予呼叫執行緒對該系統互斥機構的初始擁有權;否則,。 false

name
String

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

createdNew
Boolean

當此方法回傳時,包含一個布林值,即 true 若已建立局部互斥集(即為 namenull 為空字串),或是否已建立 false 指定的系統互斥集;若指定的系統互斥候節已存在。 這個參數會未初始化傳遞。

mutexSecurity
MutexSecurity

一個 MutexSecurity 代表要套用於命名系統互斥單元的存取控制安全性的物件。

屬性

例外狀況

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

-或-

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

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

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

命名的互斥機構存在且具備存取控制安全性,但使用者沒有 FullControl

無法建立與所提供的 name 同步物件。 不同類型的同步物件可能名稱相同。

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

範例

以下程式碼範例展示了具存取控制安全性的命名互斥架的跨程序行為。 範例使用 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 name ,且命名空間中已有該請求類型的同步物件,則會使用現有的同步物件。 如果命名空間中已有不同類型的同步物件,則會拋出 a WaitHandleCannotBeOpenedException 。 否則,會建立一個新的同步物件。

name 不是nullinitiallyOwned且且 ,true則呼叫執行緒只有在createdNew呼叫後 才true擁有命名的互斥體。 否則執行緒可透過呼叫 WaitOne 方法請求靜止子。

使用此建構子在命名系統 mutex 建立時,對其套用存取控制安全性,防止其他程式碼控制該 mutex。

此建構器初始化一個 Mutex 代表命名系統互斥的物件。 你可以建立多個 Mutex 物件,代表同一個名稱的系統互斥。

若命名系統互斥機構不存在,則以指定的存取控制安全性建立。 若存在命名的互斥體,則忽略指定的存取控制安全性。

備註

即使Mutex呼叫者拒絕或未授予當前使用者部分存取權限,仍能完全控制新建立mutexSecurity的物件。 然而,如果目前使用者嘗試使用構造子或 Mutex 方法,取得另一個 OpenExisting 物件來表示同名的互斥體,則會套用Windows存取控制安全性。

若已建立已具存取控制安全的命名互斥組,且呼叫者尚未具備 MutexRights.FullControl,則會拋出例外。 若要以僅需同步執行緒活動所需的權限開啟現有的命名互斥機構,請參見此 OpenExisting 方法。

如果你指定 null 或 一個空字串 , name會建立一個局部互斥,就像你呼叫 Mutex(Boolean) 了建構子一樣。 在此情況下, createdNew 總是 true

由於它們是系統性的,命名互斥組可用來協調跨流程邊界的資源使用。

備註

在執行終端服務的伺服器上,命名的系統mutex可以有兩層可視性。 若其名稱以前綴 Global\開頭,該互斥在所有終端伺服器會話中可見。 若其名稱以前綴 Local\開頭,該互斥僅在建立該終端伺服器會話中可見。 在這種情況下,伺服器上其他終端伺服器會話中可以存在一個同名的獨立互斥機構。 如果你在建立命名的互斥組織時未指定前綴,則會取用前綴 Local\。 在終端伺服器會話中,兩個僅以前綴名稱不同的互斥是獨立的互斥,且兩者皆對終端伺服器會話中的所有程序可見。 也就是說,前綴名稱 Global\Local\ 描述了 mutex 名稱相對於終端伺服器會話的範圍,而非相對於程序的範圍。

Caution

預設情況下,命名的互斥機構不會限制於建立它的使用者。 其他使用者可能能夠開啟並使用互斥體,包括透過進入互斥體而不退出來干擾該互斥體。 要限制特定使用者的存取,可以在建立命名的 mutex 時傳遞 a MutexSecurity 。 避免在可能有不受信任使用者執行程式碼的系統中使用無存取限制的命名互斥節。

反斜線(\)是變音子名稱中的保留字元。 除非在終端伺服器會話中使用互斥位的說明中另有說明,否則不要在互斥位名稱中使用反斜線(\)。 否則,即使 mutex 名稱代表已存在的檔案,也可能拋出 a DirectoryNotFoundException

適用於

Mutex(Boolean, String, NamedWaitHandleOptions, Boolean)

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

初始化一個新的類別實例 Mutex ,並以布林值表示呼叫執行緒是否應擁有該互斥節的初始擁有權、一個作為互斥節名稱的字串、設定使用者範圍與會話範圍存取的選項,以及一個布林值,當方法回傳時,表示呼叫執行緒是否獲得了該互斥節的初始擁有權。

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

參數

initiallyOwned
Boolean

true若命名系統互斥器是因呼叫而產生,則賦予呼叫執行緒對該系統互斥機構的初始擁有權;否則,。 false

name
String

若同步物件要與其他程序共享,則使用名稱;否則, null 或空字串。 名稱會區分大小寫。

options
NamedWaitHandleOptions

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

createdNew
Boolean

當此方法回傳時,包含一個布林值,表示 true 是否建立了本地互斥式(即 name 若是 null 或空字串),或是否建立了指定的命名系統互斥體;包含 false 若指定的系統互斥體已存在。 這個參數會未初始化傳遞。

例外狀況

命名的互斥機構存在且具備存取控制安全性,但使用者沒有 FullControl

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

-或-

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

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

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

無法建立與所提供的 name 同步物件。 不同類型的同步物件可能名稱相同。 -或-

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

備註

若已提供 a name ,且命名空間中已有請求類型的同步物件,則使用現有的同步物件;但若 options 指定存取權限僅限於目前使用者且同步物件不相容,則拋出 a WaitHandleCannotBeOpenedException 。 如果命名空間中已經存在不同類型的同步物件,也會拋出 a WaitHandleCannotBeOpenedException 。 否則,會建立一個新的同步物件。

name 不是nullinitiallyOwned且且 ,true則呼叫執行緒只有在createdNew呼叫後 才true擁有命名的互斥體。 否則執行緒可透過呼叫 WaitOne 方法請求靜止子。

此建構器初始化一個 Mutex 代表命名系統互斥的物件。 你可以建立多個 Mutex 物件,代表同一個名稱的系統互斥。

如果已建立已具備存取控制安全的命名互斥組,且呼叫者沒有 MutexRights.FullControl 權限,則會拋出例外。 若要以僅需同步執行緒活動所需的權限開啟現有的命名互斥機構,請參見此 OpenExisting 方法。

如果你指定 null 或 一個空字串 , name會建立一個局部互斥,就像你呼叫 Mutex(Boolean) 了建構子一樣。 在此情況下, createdNew 總是 true

由於它們是系統性的,命名互斥組可用來協調跨流程邊界的資源使用。

options參數可用來指定命名的互斥節是僅對當前使用者開放,還是所有使用者都能存取。 它也允許你指定指定的互斥區是只對當前會話中的程序可存取,還是所有會話都能存取。 如需詳細資訊,請參閱NamedWaitHandleOptions

另請參閱

  • 管理的執行緒
  • Mutex

適用於