Mutex 建構函式

定義

初始化 Mutex 類別的新執行個體。Initializes a new instance of the Mutex class.

多載

Mutex()

使用預設屬性,初始化 Mutex 類別的新執行個體。Initializes a new instance of the Mutex class with default properties.

Mutex(Boolean)

使用布林值 (Boolean),初始化 Mutex 類別的新執行個體,指出呼叫執行緒是否應該具有 Mutex 的初始擁有權。Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex.

Mutex(Boolean, String)

使用布林值,初始化 Mutex 類別的新執行個體,指出呼叫執行緒是否應該具有 Mutex 的初始擁有權,並擁有為 Mutex 名稱的字串。Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, and a string that is the name of the mutex.

Mutex(Boolean, String, Boolean)

使用表示呼叫執行緒是否應該具有 Mutex 的初始擁有權的布林值、代表 Mutex 名稱的字串,以及當方法傳回時表示是否將 Mutex 的初始擁有權授與呼叫執行緒的布林值,初始化 Mutex 類別的新執行個體。Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, a string that is the name of the mutex, and a Boolean value that, when the method returns, indicates whether the calling thread was granted initial ownership of the mutex.

Mutex(Boolean, String, Boolean, MutexSecurity)

使用表示呼叫執行緒是否應該具有 Mutex 的初始擁有權的布林值、代表 Mutex 名稱的字串、當這個方法傳回時表示是否將 Mutex 的初始擁有權授與呼叫執行緒的布林值,以及要套用至具名 Mutex 的存取控制安全性,初始化 Mutex 類別的新執行個體。Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, a string that is the name of the mutex, a Boolean variable that, when the method returns, indicates whether the calling thread was granted initial ownership of the mutex, and the access control security to be applied to the named mutex.

Mutex()

使用預設屬性,初始化 Mutex 類別的新執行個體。Initializes a new instance of the Mutex class with default properties.

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

範例

下列程式碼範例顯示如何使用本機 Mutex 物件來同步存取受保護的資源。The following code example shows how a local Mutex object is used to synchronize access to a protected resource. 建立 mutex 的執行緒一開始並不會有它。The thread that creates the mutex does not own it initially.

// This example shows how a Mutex is used to synchronize access
// to a protected resource. Unlike Monitor, Mutex can be used with
// WaitHandle.WaitAll and WaitAny, and can be passed across
// AppDomain boundaries.
using namespace System;
using namespace System::Threading;
const int numIterations = 1;
const int numThreads = 3;
ref class Test
{
public:

   // Create a new Mutex. The creating thread does not own the
   // Mutex.
   static Mutex^ mut = gcnew Mutex;
   static void MyThreadProc()
   {
      for ( int i = 0; i < numIterations; i++ )
      {
         UseResource();

      }
   }


private:

   // This method represents a resource that must be synchronized
   // so that only one thread at a time can enter.
   static void UseResource()
   {
      
      //Wait until it is OK to enter.
      mut->WaitOne();
      Console::WriteLine( "{0} has entered protected the area", Thread::CurrentThread->Name );
      
      // Place code to access non-reentrant resources here.
      // Simulate some work.
      Thread::Sleep( 500 );
      Console::WriteLine( "{0} is leaving protected the area\r\n", Thread::CurrentThread->Name );
      
      // Release the Mutex.
      mut->ReleaseMutex();
   }

};

int main()
{
   
   // Create the threads that will use the protected resource.
   for ( int i = 0; i < numThreads; i++ )
   {
      Thread^ myThread = gcnew Thread( gcnew ThreadStart( Test::MyThreadProc ) );
      myThread->Name = String::Format( "Thread {0}", i + 1 );
      myThread->Start();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    End Sub

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

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

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

        ' Place code to access non-reentrant resources here.

        ' Simulate some work
        Thread.Sleep(500)

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

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

備註

呼叫此函式多載與呼叫函式多載 Mutex(Boolean) ,以及指定 false 給 mutex 的初始擁有權相同。Calling this constructor overload is the same as calling the Mutex(Boolean) constructor overload and specifying false for initial ownership of the mutex. 也就是說,呼叫的執行緒不會擁有 mutex。That is, the calling thread does not own the mutex.

適用於

Mutex(Boolean)

使用布林值 (Boolean),初始化 Mutex 類別的新執行個體,指出呼叫執行緒是否應該具有 Mutex 的初始擁有權。Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex.

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

參數

initiallyOwned
Boolean

如果要把 Mutex 的初始擁有權提供給呼叫執行緒,則為 true,否則為 falsetrue to give the calling thread initial ownership of the mutex; otherwise, false.

範例

下列程式碼範例顯示如何使用本機 Mutex 物件來同步存取受保護的資源。The following code example shows how a local Mutex object is used to synchronize access to a protected resource. 建立的執行緒一 Mutex 開始會擁有它。The thread that creates the Mutex owns it initially.

using namespace System;
using namespace System::Threading;

const int numIterations = 1;
const int numThreads = 3;

ref class Test
{
public:

   // Create a new Mutex. The creating thread owns the
   // Mutex.
   static Mutex^ mut = gcnew Mutex( true );
   static void MyThreadProc()
   {
      for ( int i = 0; i < numIterations; i++ )
      {
         UseResource();

      }
   }


private:

   // This method represents a resource that must be synchronized
   // so that only one thread at a time can enter.
   static void UseResource()
   {
      
      //Wait until it is OK to enter.
      mut->WaitOne();
      Console::WriteLine( "{0} has entered protected the area", Thread::CurrentThread->Name );
      
      // Place code to access non-reentrant resources here.
      // Simulate some work.
      Thread::Sleep( 500 );
      Console::WriteLine( "{0} is leaving protected the area\r\n", Thread::CurrentThread->Name );
      
      // Release the Mutex.
      mut->ReleaseMutex();
   }

};

int main()
{
   
   // Initialize the Mutex.
   Mutex^ mut = Test::mut;
   
   // Create the threads that will use the protected resource.
   for ( int i = 0; i < numThreads; i++ )
   {
      Thread^ myThread = gcnew Thread( gcnew ThreadStart( Test::MyThreadProc ) );
      myThread->Name = String::Format( "Thread {0}", i + 1 );
      myThread->Start();

   }
   
   // Wait one second before allowing other threads to
   // acquire the Mutex.
   Console::WriteLine( "Creating thread owns the Mutex." );
   Thread::Sleep( 1000 );
   Console::WriteLine( "Creating thread releases the Mutex.\r\n" );
   mut->ReleaseMutex();
}
// The example displays output like the following:
//       Creating thread owns the Mutex.
//       Creating thread releases the Mutex.
//       
//       Thread1 has entered the protected area
//       Thread1 is leaving the protected area
//       
//       Thread2 has entered the protected area
//       Thread2 is leaving the protected area
//       
//       Thread3 has entered the protected area
//       Thread3 is leaving the protected area
using System;
using System.Threading;

class Test
{
    // Create a new Mutex. The creating thread owns the Mutex.
    private static Mutex mut = new Mutex(true);
    private const int numIterations = 1;
    private const int numThreads = 3;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        ' Place code to access non-reentrant resources here.

        ' Simulate some work
        Thread.Sleep(500)

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

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

適用於

Mutex(Boolean, String)

使用布林值,初始化 Mutex 類別的新執行個體,指出呼叫執行緒是否應該具有 Mutex 的初始擁有權,並擁有為 Mutex 名稱的字串。Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, and a string that is the name of the mutex.

public:
 Mutex(bool initiallyOwned, System::String ^ name);
[System.Security.SecurityCritical]
public Mutex (bool initiallyOwned, string name);
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 表示如果這個呼叫的結果建立了具名系統 Mutex,則將具名系統 Mutex 的初始擁有權授與呼叫執行緒,否則為 falsetrue to give the calling thread initial ownership of the named system mutex if the named system mutex is created as a result of this call; otherwise, false.

name
String

如果同步物件要與其他處理序共用,則為名稱;否則為 null 或空字串。The name, if the synchronization object is to be shared with other processes; otherwise, null or an empty string. 名稱區分大小寫。The name is case-sensitive.

屬性

例外狀況

具名 Mutex 已存在,並且具有存取控制安全性,但使用者沒有 FullControlThe named mutex exists and has access control security, but the user does not have FullControl.

name 無效。name is invalid. 這可能基於數種原因,其中包括可能由作業系統設定的一些限制,例如未知前置詞或無效字元。This can be for various reasons, including some restrictions that may be placed by the operating system, such as an unknown prefix or invalid characters. 請注意,名稱與通用前置詞 "Global" 與 "Local" 會區分大小寫。Note that the name and common prefixes "Global" and "Local" are case-sensitive.

-或--or-

發生一些其他錯誤。There was some other error. HResult 屬性可提供詳細資訊。The HResult property may provide more information.

僅限 Windows:name 已指定未知命名空間。Windows only: name specified an unknown namespace. 請參閱物件名稱 (英文) 以取得詳細資訊。See Object Names for more information.

name 太長。The name is too long. 長度限制可能會取決於作業系統或設定。Length restrictions may depend on the operating system or configuration.

無法建立具有所提供 name 的同步物件。A synchronization object with the provided name cannot be created. 不同類型的同步物件可能具有相同名稱。A synchronization object of a different type might have the same name.

僅限 .NET Framework:name 的長度超過 MAX_PATH (260 個字元)。.NET Framework only: name is longer than MAX_PATH (260 characters).

範例

下列範例顯示如何使用命名 mutex,在兩個不同進程中執行的執行緒之間發出信號。The following example shows how a named mutex is used to signal between threads running in two separate processes.

從兩個或多個命令視窗執行此程式。Run this program from two or more command windows. 每個進程都會建立 Mutex 代表已命名 mutex 的物件 MyMutexEach process creates a Mutex object that represents the named mutex MyMutex. 命名 mutex 是系統物件,其存留期是由代表它的物件存留期所限定 MutexThe named mutex is a system object whose lifetime is bounded by the lifetimes of the Mutex objects that represent it. 當第一個進程建立物件時,會建立命名 mutex Mutex ; 在此範例中,命名 mutex 是由執行程式的第一個進程所擁有。The named mutex is created when the first process creates its Mutex object; in this example, the named mutex is owned by the first process that runs the program. 當所有代表該物件的物件都已釋出時,就會終結該命名 mutex MutexThe named mutex is destroyed when all the Mutex objects that represent it have been released.

此範例中使用的函式多載無法告知呼叫執行緒是否已授與已命名 mutex 的初始擁有權。The constructor overload used in this example cannot tell the calling thread whether initial ownership of the named mutex was granted. 除非您確定執行緒將會建立已命名的 mutex,否則您不應該使用這個函式來要求初始擁有權。You should not use this constructor to request initial ownership unless you can be certain that the thread will create the named mutex.

using namespace System;
using namespace System::Threading;

int main()
{
   // Create the named mutex. Only one system object named 
   // "MyMutex" can exist; the local Mutex object represents 
   // this system object, regardless of which process or thread
   // caused "MyMutex" to be created.
   Mutex^ m = gcnew Mutex( false,"MyMutex" );
   
   // Try to gain control of the named mutex. If the mutex is 
   // controlled by another thread, wait for it to be released.        
   Console::WriteLine(  "Waiting for the Mutex." );
   m->WaitOne();
   
   // Keep control of the mutex until the user presses
   // ENTER.
   Console::WriteLine( "This application owns the mutex. "
   "Press ENTER to release the mutex and exit." );
   Console::ReadLine();
   m->ReleaseMutex();
}

using System;
using System.Threading;

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

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

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

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

備註

name可能會在前面加上 Global\Local\ 來指定命名空間。The name may be prefixed with Global\ or Local\ to specify a namespace. Global指定命名空間時,同步處理物件可能會與系統上的任何處理程式共用。When the Global namespace is specified, the synchronization object may be shared with any processes on the system. Local 指定命名空間時,如果未指定命名空間,這也是預設值,則可以與相同會話中的處理常式共用同步處理物件。When the Local namespace is specified, which is also the default when no namespace is specified, the synchronization object may be shared with processes in the same session. 在 Windows 上,會話是登入會話,而服務通常會在不同的非互動式會話中執行。On Windows, a session is a login session, and services typically run in a different non-interactive session. 在類似 Unix 的作業系統上,每個 shell 都有自己的會話。On Unix-like operating systems, each shell has its own session. 會話本機同步處理物件可能適合用來在具有父/子關聯性的進程之間進行同步處理,而且它們都會在相同的會話中執行。Session-local synchronization objects may be appropriate for synchronizing between processes with a parent/child relationship where they all run in the same session. 如需有關在 Windows 上 synchornization 物件名稱的詳細資訊,請參閱 物件名稱For more information about synchornization object names on Windows, see Object Names.

如果 name 已提供,且命名空間中已有所要求類型的同步處理物件存在,就會使用現有的同步處理物件。If a name is provided and a synchronization object of the requested type already exists in the namespace, the existing synchronization object is used. 如果命名空間中已經有不同類型的同步處理物件存在, WaitHandleCannotBeOpenedException 就會擲回。If a synchronization object of a different type already exists in the namespace, a WaitHandleCannotBeOpenedException is thrown. 否則會建立新的同步處理物件。Otherwise, a new synchronization object is created.

如果不 namenullinitiallyOwnedtrue ,則呼叫執行緒只會在指定的系統 mutex 是因為此呼叫而建立時,才擁有 mutex。If name is not null and initiallyOwned is true, the calling thread owns the mutex only if the named system mutex was created as a result of this call. 因為沒有任何機制可判斷是否已建立命名系統 mutex,所以最好在呼叫這個函式多載 false 時指定 for initiallyOwnedSince there is no mechanism for determining whether the named system mutex was created, it is better to specify false for initiallyOwned when calling this constructor overload. Mutex(Boolean, String, Boolean)如果您需要判斷初始擁有權,您可以使用此函式。You can use the Mutex(Boolean, String, Boolean) constructor if you need to determine initial ownership.

這個函式 Mutex 會初始化代表命名系統 mutex 的物件。This constructor initializes a Mutex object that represents a named system mutex. 您可以建立多個 Mutex 代表相同命名系統 mutex 的物件。You can create multiple Mutex objects that represent the same named system mutex.

如果已建立具有存取控制安全性的已命名 mutex,而且呼叫端沒有,則會擲回 MutexRights.FullControl 例外狀況。If the named mutex has already been created with access control security, and the caller does not have MutexRights.FullControl, an exception is thrown. 若要使用同步處理執行緒活動所需的許可權來開啟現有的已命名 mutex,請參閱 OpenExisting 方法。To open an existing named mutex with only those permissions needed for synchronizing thread activities, see the OpenExisting method.

如果您指定 null 或的空字串 name ,則會建立本機 mutex,就像您呼叫此函式一樣 Mutex(Boolean)If you specify null or an empty string for name, a local mutex is created, as if you had called the Mutex(Boolean) constructor. 在此情況下, createdNew 一律為 trueIn this case, createdNew is always true.

因為它們是全系統,所以命名的 mutex 可以用來協調跨進程界限的資源使用。Because they are system-wide, named mutexes can be used to coordinate resource use across process boundaries.

注意

在執行終端機服務的伺服器上,名為系統 mutex 可以有兩個層級的可見度。On a server that is running Terminal Services, a named system mutex can have two levels of visibility. 如果其名稱開頭為 "Global" 前置詞 \ ,則在所有終端機伺服器會話中都可以看到 mutex。If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. 如果其名稱開頭為 "Local" 前置詞 \ ,則 mutex 只會顯示在其建立所在的終端機伺服器會話中。If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created. 在此情況下,伺服器上的每個其他終端機伺服器會話中都可以存在具有相同名稱的個別 mutex。In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server. 如果您在建立命名 mutex 時未指定前置詞,則會接受前置詞 "Local \ "。If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\". 在終端機伺服器會話中,有兩個不同的 mutex,其名稱只有各自的前置詞不同,而且在終端機伺服器會話中的所有進程都可以看到兩者。Within a terminal server session, two mutexes whose names differ only by their prefixes are separate mutexes, and both are visible to all processes in the terminal server session. 也就是說,前置詞名稱 "Global \ " 和 "Local \ " 會描述相對於終端機伺服器會話之 mutex 名稱的範圍,而不是相對於處理常式。That is, the prefix names "Global\" and "Local\" describe the scope of the mutex name relative to terminal server sessions, not relative to processes.

反斜線 (\) 是 Mutex 名稱的保留字元。The backslash (\) is a reserved character in a mutex name. 請勿在 Mutex 名稱中使用反斜線 (\),除非在終端機伺服器工作階段中使用 Mutex 的注意事項中有指定。Don't use a backslash (\) in a mutex name except as specified in the note on using mutexes in terminal server sessions. 否則,可能會擲回 DirectoryNotFoundException,即使是 Mutex 的名稱代表現有的檔案。Otherwise, a DirectoryNotFoundException may be thrown, even though the name of the mutex represents an existing file.

適用於

Mutex(Boolean, String, Boolean)

使用表示呼叫執行緒是否應該具有 Mutex 的初始擁有權的布林值、代表 Mutex 名稱的字串,以及當方法傳回時表示是否將 Mutex 的初始擁有權授與呼叫執行緒的布林值,初始化 Mutex 類別的新執行個體。Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, a string that is the name of the mutex, and a Boolean value that, when the method returns, indicates whether the calling thread was granted initial ownership of the mutex.

public:
 Mutex(bool initiallyOwned, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew);
[System.Security.SecurityCritical]
public Mutex (bool initiallyOwned, string name, out bool createdNew);
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 表示如果這個呼叫的結果建立了具名系統 Mutex,則將具名系統 Mutex 的初始擁有權授與呼叫執行緒,否則為 falsetrue to give the calling thread initial ownership of the named system mutex if the named system mutex is created as a result of this call; otherwise, false.

name
String

如果同步物件要與其他處理序共用,則為名稱;否則為 null 或空字串。The name, if the synchronization object is to be shared with other processes; otherwise, null or an empty string. 名稱區分大小寫。The name is case-sensitive.

createdNew
Boolean

當這個方法傳回時,如果已建立本機 Mutex (也就是說,如果 namenull 或空字串),或是已建立指定的具名系統 Mutex,則會包含 true 的布林值;如果指定的具名系統 Mutex 已存在,則為 falseWhen this method returns, contains a Boolean that is true if a local mutex was created (that is, if name is null or an empty string) or if the specified named system mutex was created; false if the specified named system mutex already existed. 這個參數會以未初始化的狀態傳遞。This parameter is passed uninitialized.

屬性

例外狀況

具名 Mutex 已存在,並且具有存取控制安全性,但使用者沒有 FullControlThe named mutex exists and has access control security, but the user does not have FullControl.

name 無效。name is invalid. 這可能基於數種原因,其中包括可能由作業系統設定的一些限制,例如未知前置詞或無效字元。This can be for various reasons, including some restrictions that may be placed by the operating system, such as an unknown prefix or invalid characters. 請注意,名稱與通用前置詞 "Global" 與 "Local" 會區分大小寫。Note that the name and common prefixes "Global" and "Local" are case-sensitive.

-或--or-

發生一些其他錯誤。There was some other error. HResult 屬性可提供詳細資訊。The HResult property may provide more information.

僅限 Windows:name 已指定未知命名空間。Windows only: name specified an unknown namespace. 請參閱物件名稱 (英文) 以取得詳細資訊。See Object Names for more information.

name 太長。The name is too long. 長度限制可能會取決於作業系統或設定。Length restrictions may depend on the operating system or configuration.

無法建立具有所提供 name 的同步物件。A synchronization object with the provided name cannot be created. 不同類型的同步物件可能具有相同名稱。A synchronization object of a different type might have the same name.

僅限 .NET Framework:name 的長度超過 MAX_PATH (260 個字元)。.NET Framework only: name is longer than MAX_PATH (260 characters).

範例

下列程式碼範例會示範如何使用命名 mutex 來表示進程或執行緒之間的信號。The following code example shows how a named mutex is used to signal between processes or threads. 從兩個或多個命令視窗執行此程式。Run this program from two or more command windows. 每個進程都會建立 Mutex 代表已命名 mutex "MyMutex" 的物件。Each process creates a Mutex object that represents the named mutex "MyMutex". 命名 mutex 是系統物件。The named mutex is a system object. 在此範例中,其存留期是由代表它的物件存留期所限制 MutexIn this example, its lifetime is bounded by the lifetimes of the Mutex objects that represent it. 當第一個進程建立其本機物件時,會建立命名 mutex Mutex ,並且在所有 Mutex 代表它的物件都已釋放時終結。The named mutex is created when the first process creates its local Mutex object, and destroyed when all the Mutex objects that represent it have been released. 命名 mutex 最初是由第一個進程所擁有。The named mutex is initially owned by the first process. 第二個程式和任何後續的進程會等候先前的處理常式釋出已命名的 mutex。The second process and any subsequent processes wait for earlier processes to release the named mutex.

// This example shows how a named mutex is used to signal between
// processes or threads.
// Run this program from two (or more) command windows. Each process
// creates a Mutex object that represents the named mutex "MyMutex".
// The named mutex is a system object whose lifetime is bounded by the
// lifetimes of the Mutex objects that represent it. The named mutex
// is created when the first process creates its local Mutex; in this
// example, the named mutex is owned by the first process. The named 
// mutex is destroyed when all the Mutex objects that represent it
// have been released. 
// The second process (and any subsequent process) waits for earlier
// processes to release the named mutex.
using namespace System;
using namespace System::Threading;
int main()
{
   
   // Set this variable to false if you do not want to request 
   // initial ownership of the named mutex.
   bool requestInitialOwnership = true;
   bool mutexWasCreated;
   
   // Request initial ownership of the named mutex by passing
   // true for the first parameter. Only one system object named 
   // "MyMutex" can exist; the local Mutex object represents 
   // this system object. If "MyMutex" is created by this call,
   // then mutexWasCreated contains true; otherwise, it contains
   // false.
   Mutex^ m = gcnew Mutex( requestInitialOwnership, "MyMutex", mutexWasCreated );
   
   // This thread owns the mutex only if it both requested 
   // initial ownership and created the named mutex. Otherwise,
   // it can request the named mutex by calling WaitOne.
   if (  !(requestInitialOwnership && mutexWasCreated) )
   {
      Console::WriteLine(  "Waiting for the named mutex." );
      m->WaitOne();
   }

   
   // Once the process has gained control of the named mutex,
   // hold onto it until the user presses ENTER.
   Console::WriteLine(  "This process owns the named mutex. "
    "Press ENTER to release the mutex and exit." );
   Console::ReadLine();
   
   // Call ReleaseMutex to allow other threads to gain control
   // of the named mutex. If you keep a reference to the local
   // Mutex, you can call WaitOne to request control of the 
   // named mutex.
   m->ReleaseMutex();
}

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

using System;
using System.Threading;

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

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

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

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

Imports System.Threading

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

備註

name可能會在前面加上 Global\Local\ 來指定命名空間。The name may be prefixed with Global\ or Local\ to specify a namespace. Global指定命名空間時,同步處理物件可能會與系統上的任何處理程式共用。When the Global namespace is specified, the synchronization object may be shared with any processes on the system. Local 指定命名空間時,如果未指定命名空間,這也是預設值,則可以與相同會話中的處理常式共用同步處理物件。When the Local namespace is specified, which is also the default when no namespace is specified, the synchronization object may be shared with processes in the same session. 在 Windows 上,會話是登入會話,而服務通常會在不同的非互動式會話中執行。On Windows, a session is a login session, and services typically run in a different non-interactive session. 在類似 Unix 的作業系統上,每個 shell 都有自己的會話。On Unix-like operating systems, each shell has its own session. 會話本機同步處理物件可能適合用來在具有父/子關聯性的進程之間進行同步處理,而且它們都會在相同的會話中執行。Session-local synchronization objects may be appropriate for synchronizing between processes with a parent/child relationship where they all run in the same session. 如需有關在 Windows 上 synchornization 物件名稱的詳細資訊,請參閱 物件名稱For more information about synchornization object names on Windows, see Object Names.

如果 name 已提供,且命名空間中已有所要求類型的同步處理物件存在,就會使用現有的同步處理物件。If a name is provided and a synchronization object of the requested type already exists in the namespace, the existing synchronization object is used. 如果命名空間中已經有不同類型的同步處理物件存在, WaitHandleCannotBeOpenedException 就會擲回。If a synchronization object of a different type already exists in the namespace, a WaitHandleCannotBeOpenedException is thrown. 否則會建立新的同步處理物件。Otherwise, a new synchronization object is created.

如果不 namenullinitiallyOwnedtrue ,則只有在 createdNew 呼叫之後,呼叫執行緒才會擁有已命名的 mutex trueIf name is not null and initiallyOwned is true, the calling thread owns the named mutex only if createdNew is true after the call. 否則,執行緒可以藉由呼叫方法來要求 mutex WaitOneOtherwise the thread can request the mutex by calling the WaitOne method.

這個函式 Mutex 會初始化代表命名系統 mutex 的物件。This constructor initializes a Mutex object that represents a named system mutex. 您可以建立多個 Mutex 代表相同命名系統 mutex 的物件。You can create multiple Mutex objects that represent the same named system mutex.

如果已建立具有存取控制安全性的已命名 mutex,且呼叫端沒有 MutexRights.FullControl 許可權,則會擲回例外狀況。If the named mutex has already been created with access control security, and the caller does not have MutexRights.FullControl rights, an exception is thrown. 若要使用同步處理執行緒活動所需的許可權來開啟現有的已命名 mutex,請參閱 OpenExisting 方法。To open an existing named mutex with only those permissions needed for synchronizing thread activities, see the OpenExisting method.

如果您指定 null 或的空字串 name ,則會建立本機 mutex,就像您呼叫此函式一樣 Mutex(Boolean)If you specify null or an empty string for name, a local mutex is created, as if you had called the Mutex(Boolean) constructor. 在此情況下, createdNew 一律為 trueIn this case, createdNew is always true.

因為它們是全系統,所以命名的 mutex 可以用來協調跨進程界限的資源使用。Because they are system-wide, named mutexes can be used to coordinate resource use across process boundaries.

注意

在執行終端機服務的伺服器上,名為系統 mutex 可以有兩個層級的可見度。On a server that is running Terminal Services, a named system mutex can have two levels of visibility. 如果其名稱開頭為 "Global" 前置詞 \ ,則在所有終端機伺服器會話中都可以看到 mutex。If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. 如果其名稱開頭為 "Local" 前置詞 \ ,則 mutex 只會顯示在其建立所在的終端機伺服器會話中。If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created. 在此情況下,伺服器上的每個其他終端機伺服器會話中都可以存在具有相同名稱的個別 mutex。In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server. 如果您在建立命名 mutex 時未指定前置詞,則會接受前置詞 "Local \ "。If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\". 在終端機伺服器會話中,有兩個不同的 mutex,其名稱只有各自的前置詞不同,而且在終端機伺服器會話中的所有進程都可以看到兩者。Within a terminal server session, two mutexes whose names differ only by their prefixes are separate mutexes, and both are visible to all processes in the terminal server session. 也就是說,前置詞名稱 "Global \ " 和 "Local \ " 會描述相對於終端機伺服器會話之 mutex 名稱的範圍,而不是相對於處理常式。That is, the prefix names "Global\" and "Local\" describe the scope of the mutex name relative to terminal server sessions, not relative to processes.

反斜線 (\) 是 Mutex 名稱的保留字元。The backslash (\) is a reserved character in a mutex name. 請勿在 Mutex 名稱中使用反斜線 (\),除非在終端機伺服器工作階段中使用 Mutex 的注意事項中有指定。Don't use a backslash (\) in a mutex name except as specified in the note on using mutexes in terminal server sessions. 否則,可能會擲回 DirectoryNotFoundException,即使是 Mutex 的名稱代表現有的檔案。Otherwise, a DirectoryNotFoundException may be thrown, even though the name of the mutex represents an existing file.

適用於

Mutex(Boolean, String, Boolean, MutexSecurity)

使用表示呼叫執行緒是否應該具有 Mutex 的初始擁有權的布林值、代表 Mutex 名稱的字串、當這個方法傳回時表示是否將 Mutex 的初始擁有權授與呼叫執行緒的布林值,以及要套用至具名 Mutex 的存取控制安全性,初始化 Mutex 類別的新執行個體。Initializes a new instance of the Mutex class with a Boolean value that indicates whether the calling thread should have initial ownership of the mutex, a string that is the name of the mutex, a Boolean variable that, when the method returns, indicates whether the calling thread was granted initial ownership of the mutex, and the access control security to be applied to the named mutex.

public:
 Mutex(bool initiallyOwned, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew, System::Security::AccessControl::MutexSecurity ^ mutexSecurity);
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 表示如果這個呼叫的結果建立了具名系統 Mutex,則將具名系統 Mutex 的初始擁有權授與呼叫執行緒,否則為 falsetrue to give the calling thread initial ownership of the named system mutex if the named system mutex is created as a result of this call; otherwise, false.

name
String

如果同步物件要與其他處理序共用,則為名稱;否則為 null 或空字串。The name, if the synchronization object is to be shared with other processes; otherwise, null or an empty string. 名稱區分大小寫。The name is case-sensitive.

createdNew
Boolean

當這個方法傳回時,如果已建立本機 Mutex (也就是說,如果 namenull 或空字串),或是已建立指定的具名系統 Mutex,則會包含 true 的布林值;如果指定的具名系統 Mutex 已存在,則為 falseWhen this method returns, contains a Boolean that is true if a local mutex was created (that is, if name is null or an empty string) or if the specified named system mutex was created; false if the specified named system mutex already existed. 這個參數會以未初始化的狀態傳遞。This parameter is passed uninitialized.

mutexSecurity
MutexSecurity

MutexSecurity 物件,代表要套用至具名系統 Mutex 的存取控制安全性。A MutexSecurity object that represents the access control security to be applied to the named system mutex.

屬性

例外狀況

name 無效。name is invalid. 這可能基於數種原因,其中包括可能由作業系統設定的一些限制,例如未知前置詞或無效字元。This can be for various reasons, including some restrictions that may be placed by the operating system, such as an unknown prefix or invalid characters. 請注意,名稱與通用前置詞 "Global" 與 "Local" 會區分大小寫。Note that the name and common prefixes "Global" and "Local" are case-sensitive.

-或--or-

發生一些其他錯誤。There was some other error. HResult 屬性可提供詳細資訊。The HResult property may provide more information.

僅限 Windows:name 已指定未知命名空間。Windows only: name specified an unknown namespace. 請參閱物件名稱 (英文) 以取得詳細資訊。See Object Names for more information.

name 太長。The name is too long. 長度限制可能會取決於作業系統或設定。Length restrictions may depend on the operating system or configuration.

具名 Mutex 已存在,並且具有存取控制安全性,但使用者沒有 FullControlThe named mutex exists and has access control security, but the user does not have FullControl.

無法建立具有所提供 name 的同步物件。A synchronization object with the provided name cannot be created. 不同類型的同步物件可能具有相同名稱。A synchronization object of a different type might have the same name.

僅限 .NET Framework:name 的長度超過 MAX_PATH (260 個字元)。.NET Framework only: name is longer than MAX_PATH (260 characters).

範例

下列程式碼範例示範具有存取控制安全性之已命名 mutex 的跨進程行為。The following code example demonstrates the cross-process behavior of a named mutex with access control security. 此範例會使用 OpenExisting(String) 方法多載來測試已命名 mutex 是否存在。The example uses the OpenExisting(String) method overload to test for the existence of a named mutex.

如果 mutex 不存在,就會以初始擁有權和存取控制安全性來建立,此安全性會拒絕目前使用者使用 mutex 的許可權,但會授與 mutex 讀取和變更許可權的許可權。If the mutex does not exist, it is created with initial ownership and access control security that denies the current user the right to use the mutex, but grants the right to read and change permissions on the mutex.

如果您從兩個命令視窗執行已編譯的範例,則第二個複本將會在呼叫上擲回存取違規例外狀況 OpenExisting(String)If you run the compiled example from two command windows, the second copy will throw an access violation exception on the call to OpenExisting(String). 攔截到例外狀況,而此範例會使用方法多載, OpenExisting(String, MutexRights) 以讀取和變更許可權所需的許可權來開啟 mutex。The exception is caught, and the example uses the OpenExisting(String, MutexRights) method overload to open the mutex with the rights needed to read and change the permissions.

變更許可權之後,就會以輸入和釋放所需的許可權開啟 mutex。After the permissions are changed, the mutex is opened with the rights required to enter and release it. 如果您從第三個命令視窗執行已編譯的範例,它會使用新的許可權執行。If you run the compiled example from a third command window, it runs using the new permissions.

using namespace System;
using namespace System::Threading;
using namespace System::Security::AccessControl;
using namespace System::Security::Permissions;

public ref class Example
{
public:
   [SecurityPermissionAttribute(SecurityAction::Demand,Flags=SecurityPermissionFlag::UnmanagedCode)]
   static void Main()
   {
      String^ mutexName = L"MutexExample4";

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

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

      // There are three cases: (1) The mutex does not exist.
      // (2) The mutex exists, but the current user doesn't
      // have access. (3) The mutex exists and the user has
      // access.
      //
      if ( doesNotExist )
      {
         // The mutex does not exist, so create it.
         // Create an access control list (ACL) that denies the
         // current user the right to enter or release the
         // mutex, but allows the right to read and change
         // security information for the mutex.
         //
         String^ user = String::Concat( Environment::UserDomainName, L"\\",
            Environment::UserName );
         MutexSecurity^ mSec = gcnew MutexSecurity;

         MutexAccessRule^ rule = gcnew MutexAccessRule( user,
            static_cast<MutexRights>(
               MutexRights::Synchronize |
               MutexRights::Modify),
            AccessControlType::Deny );
         mSec->AddAccessRule( rule );

         rule = gcnew MutexAccessRule( user,
            static_cast<MutexRights>(
               MutexRights::ReadPermissions |
                MutexRights::ChangePermissions),
            AccessControlType::Allow );
         mSec->AddAccessRule( rule );
         
         // Create a Mutex object that represents the system
         // mutex named by the constant 'mutexName', with
         // initial ownership for this thread, and with the
         // specified security access. The Boolean value that
         // indicates creation of the underlying system object
         // is placed in mutexWasCreated.
         //
         m = gcnew Mutex( true,mutexName, mutexWasCreated,mSec );
         
         // If the named system mutex was created, it can be
         // used by the current instance of this program, even
         // though the current user is denied access. The current
         // program owns the mutex. Otherwise, exit the program.
         //
         if ( mutexWasCreated )
         {
            Console::WriteLine( L"Created the mutex." );
         }
         else
         {
            Console::WriteLine( L"Unable to create the mutex." );
            return;
         }
      }
      else if ( unauthorized )
      {
         // Open the mutex to read and change the access control
         // security. The access control security defined above
         // allows the current user to do this.
         //
         try
         {
            m = Mutex::OpenExisting( mutexName,
               static_cast<MutexRights>(
                  MutexRights::ReadPermissions |
                  MutexRights::ChangePermissions) );
            
            // Get the current ACL. This requires
            // MutexRights.ReadPermissions.
            MutexSecurity^ mSec = m->GetAccessControl();

            String^ user = String::Concat( Environment::UserDomainName,
               L"\\", Environment::UserName );
            
            // First, the rule that denied the current user
            // the right to enter and release the mutex must
            // be removed.
            MutexAccessRule^ rule = gcnew MutexAccessRule( user,
               static_cast<MutexRights>(
                  MutexRights::Synchronize |
                  MutexRights::Modify),
               AccessControlType::Deny );
            mSec->RemoveAccessRule( rule );
            
            // Now grant the user the correct rights.
            //
            rule = gcnew MutexAccessRule( user,
               static_cast<MutexRights>(
                  MutexRights::Synchronize |
                  MutexRights::Modify),
               AccessControlType::Allow );
            mSec->AddAccessRule( rule );
            
            // Update the ACL. This requires
            // MutexRights.ChangePermissions.
            m->SetAccessControl( mSec );

            Console::WriteLine( L"Updated mutex security." );
            
            // Open the mutex with (MutexRights.Synchronize
            // | MutexRights.Modify), the rights required to
            // enter and release the mutex.
            //
            m = Mutex::OpenExisting( mutexName );
         }
         catch ( UnauthorizedAccessException^ ex ) 
         {
            Console::WriteLine(
               L"Unable to change permissions: {0}", ex->Message );
            return;
         }
      }
      
      // If this program created the mutex, it already owns
      // the mutex.
      //
      if ( !mutexWasCreated )
      {
         // Enter the mutex, and hold it until the program
         // exits.
         //
         try
         {
            Console::WriteLine( L"Wait for the mutex." );
            m->WaitOne();
            Console::WriteLine( L"Entered the mutex." );
         }
         catch ( UnauthorizedAccessException^ ex ) 
         {
            Console::WriteLine( L"Unauthorized access: {0}",
               ex->Message );
         }
      }

      Console::WriteLine( L"Press the Enter key to exit." );
      Console::ReadLine();
      m->ReleaseMutex();
      m->Dispose();
   }
};

int main()
{
   Example::Main();
}
using System;
using System.Threading;
using System.Security.AccessControl;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

Friend Class Example

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

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

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

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

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

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

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

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

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

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

        ElseIf unauthorized Then

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

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

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

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

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

                Console.WriteLine("Updated mutex security.")

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

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

        End If

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

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

備註

name可能會在前面加上 Global\Local\ 來指定命名空間。The name may be prefixed with Global\ or Local\ to specify a namespace. Global指定命名空間時,同步處理物件可能會與系統上的任何處理程式共用。When the Global namespace is specified, the synchronization object may be shared with any processes on the system. Local 指定命名空間時,如果未指定命名空間,這也是預設值,則可以與相同會話中的處理常式共用同步處理物件。When the Local namespace is specified, which is also the default when no namespace is specified, the synchronization object may be shared with processes in the same session. 在 Windows 上,會話是登入會話,而服務通常會在不同的非互動式會話中執行。On Windows, a session is a login session, and services typically run in a different non-interactive session. 在類似 Unix 的作業系統上,每個 shell 都有自己的會話。On Unix-like operating systems, each shell has its own session. 會話本機同步處理物件可能適合用來在具有父/子關聯性的進程之間進行同步處理,而且它們都會在相同的會話中執行。Session-local synchronization objects may be appropriate for synchronizing between processes with a parent/child relationship where they all run in the same session. 如需有關在 Windows 上 synchornization 物件名稱的詳細資訊,請參閱 物件名稱For more information about synchornization object names on Windows, see Object Names.

如果 name 已提供,且命名空間中已有所要求類型的同步處理物件存在,就會使用現有的同步處理物件。If a name is provided and a synchronization object of the requested type already exists in the namespace, the existing synchronization object is used. 如果命名空間中已經有不同類型的同步處理物件存在, WaitHandleCannotBeOpenedException 就會擲回。If a synchronization object of a different type already exists in the namespace, a WaitHandleCannotBeOpenedException is thrown. 否則會建立新的同步處理物件。Otherwise, a new synchronization object is created.

如果不 namenullinitiallyOwnedtrue ,則只有在 createdNew 呼叫之後,呼叫執行緒才會擁有已命名的 mutex trueIf name is not null and initiallyOwned is true, the calling thread owns the named mutex only if createdNew is true after the call. 否則,執行緒可以藉由呼叫方法來要求 mutex WaitOneOtherwise the thread can request the mutex by calling the WaitOne method.

使用此函式可在建立時將存取控制安全性套用至命名系統 mutex,以防止其他程式碼控制 mutex。Use this constructor to apply access control security to a named system mutex when it is created, preventing other code from taking control of the mutex.

這個函式 Mutex 會初始化代表命名系統 mutex 的物件。This constructor initializes a Mutex object that represents a named system mutex. 您可以建立多個 Mutex 代表相同命名系統 mutex 的物件。You can create multiple Mutex objects that represent the same named system mutex.

如果命名的系統 mutex 不存在,就會使用指定的存取控制安全性來建立。If the named system mutex does not exist, it is created with the specified access control security. 如果已命名 mutex 存在,則會忽略指定的存取控制安全性。If the named mutex exists, the specified access control security is ignored.

注意

Mutex即使 mutexSecurity 拒絕或無法授與存取權給目前的使用者,呼叫者仍能完全掌控新建立的物件。The caller has full control over the newly created Mutex object even if mutexSecurity denies or fails to grant some access rights to the current user. 但是,如果目前的使用者嘗試使用函式 Mutex 或方法,取得另一個物件來代表相同的命名 mutex, OpenExisting 則會套用 Windows 存取控制安全性。However, if the current user attempts to get another Mutex object to represent the same named mutex, using either a constructor or the OpenExisting method, Windows access control security is applied.

如果已建立具有存取控制安全性的已命名 mutex,而且呼叫端沒有,則會擲回 MutexRights.FullControl 例外狀況。If the named mutex has already been created with access control security, and the caller does not have MutexRights.FullControl, an exception is thrown. 若要使用同步處理執行緒活動所需的許可權來開啟現有的已命名 mutex,請參閱 OpenExisting 方法。To open an existing named mutex with only those permissions needed for synchronizing thread activities, see the OpenExisting method.

如果您指定 null 或的空字串 name ,則會建立本機 mutex,就像您呼叫此函式一樣 Mutex(Boolean)If you specify null or an empty string for name, a local mutex is created, as if you had called the Mutex(Boolean) constructor. 在此情況下, createdNew 一律為 trueIn this case, createdNew is always true.

因為它們是全系統,所以命名的 mutex 可以用來協調跨進程界限的資源使用。Because they are system-wide, named mutexes can be used to coordinate resource use across process boundaries.

注意

在執行終端機服務的伺服器上,名為系統 mutex 可以有兩個層級的可見度。On a server that is running Terminal Services, a named system mutex can have two levels of visibility. 如果其名稱開頭為 "Global" 前置詞 \ ,則在所有終端機伺服器會話中都可以看到 mutex。If its name begins with the prefix "Global\", the mutex is visible in all terminal server sessions. 如果其名稱開頭為 "Local" 前置詞 \ ,則 mutex 只會顯示在其建立所在的終端機伺服器會話中。If its name begins with the prefix "Local\", the mutex is visible only in the terminal server session where it was created. 在此情況下,伺服器上的每個其他終端機伺服器會話中都可以存在具有相同名稱的個別 mutex。In that case, a separate mutex with the same name can exist in each of the other terminal server sessions on the server. 如果您在建立命名 mutex 時未指定前置詞,則會接受前置詞 "Local \ "。If you do not specify a prefix when you create a named mutex, it takes the prefix "Local\". 在終端機伺服器會話中,有兩個不同的 mutex,其名稱只有各自的前置詞不同,而且在終端機伺服器會話中的所有進程都可以看到兩者。Within a terminal server session, two mutexes whose names differ only by their prefixes are separate mutexes, and both are visible to all processes in the terminal server session. 也就是說,前置詞名稱 "Global \ " 和 "Local \ " 會描述相對於終端機伺服器會話之 mutex 名稱的範圍,而不是相對於處理常式。That is, the prefix names "Global\" and "Local\" describe the scope of the mutex name relative to terminal server sessions, not relative to processes.

反斜線 (\) 是 Mutex 名稱的保留字元。The backslash (\) is a reserved character in a mutex name. 請勿在 Mutex 名稱中使用反斜線 (\),除非在終端機伺服器工作階段中使用 Mutex 的注意事項中有指定。Don't use a backslash (\) in a mutex name except as specified in the note on using mutexes in terminal server sessions. 否則,可能會擲回 DirectoryNotFoundException,即使是 Mutex 的名稱代表現有的檔案。Otherwise, a DirectoryNotFoundException may be thrown, even though the name of the mutex represents an existing file.

適用於