Mutex コンストラクター

定義

Mutex クラスの新しいインスタンスを初期化します。

オーバーロード

Mutex()

Mutex クラスの新しいインスタンスを、既定のプロパティを使用して初期化します。

Mutex(Boolean)

呼び出し元のスレッドにミューテックスの初期所有権があるかどうかを示すブール値を使用して、Mutex クラスの新しいインスタンスを初期化します。

Mutex(Boolean, String)

呼び出し元のスレッドにミューテックスの初期所有権があるかどうかを示すブール値と、ミューテックスの名前を表す文字列を使用して、Mutex クラスの新しいインスタンスを初期化します。

Mutex(Boolean, String, Boolean)

呼び出し元のスレッドにミューテックスの初期所有権があるかどうかを示すブール値、ミューテックスの名前を表す文字列、およびメソッドから戻るときにミューテックスの初期所有権が呼び出し元のスレッドに付与されたかどうかを示すブール値を指定して、Mutex クラスの新しいインスタンスを初期化します。

Mutex(Boolean, String, Boolean, MutexSecurity)

呼び出し元のスレッドにミューテックスの初期所有権があるかどうかを示すブール値、ミューテックスの名前を表す文字列、メソッドが戻るときにミューテックスの初期所有権が呼び出し元のスレッドに付与されたかどうかを示すブール値変数、および名前付きミューテックスに適用するアクセス制御セキュリティを指定して、Mutex クラスの新しいインスタンスを初期化します。

Mutex()

Source:
Mutex.cs
Source:
Mutex.cs
Source:
Mutex.cs

Mutex クラスの新しいインスタンスを、既定のプロパティを使用して初期化します。

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

次のコード例は、ローカル 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 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 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(Boolean)

Source:
Mutex.cs
Source:
Mutex.cs
Source:
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 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
{
    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(Boolean, String)

Source:
Mutex.cs
Source:
Mutex.cs
Source:
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 を持つ同期オブジェクトを作成できません。 別の型の同期オブジェクトに同じ名前が指定されている可能性があります。

.NET Frameworkのみ: name がMAX_PATH (260 文字) を超えています。

次の例では、名前付きミューテックスを使用して、2 つの別々のプロセスで実行されているスレッド間でシグナルを通知する方法を示します。

2 つ以上のコマンド ウィンドウからこのプログラムを実行します。 各プロセスでは、 Mutex 名前付きミューテックス を表す オブジェクトが作成されます MyMutex。 名前付きミューテックスは、有効期間が、それを表すオブジェクトの Mutex 有効期間によって制限されるシステム オブジェクトです。 名前付きミューテックスは、最初のプロセスがその Mutex オブジェクトを作成するときに作成されます。この例では、名前付きミューテックスは、プログラムを実行する最初のプロセスによって所有されます。 名前付きミューテックスは、それを表すすべての 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 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 に似たオペレーティング システムでは、各シェルに独自のセッションがあります。 セッションとローカルの同期オブジェクトは、プロセス間の同期に適している場合があります。これらはすべて同じセッションで実行される親子関係を持ちます。 Windows での同期オブジェクト名の詳細については、「 オブジェクト名」を参照してください。

nameが指定され、要求された型の同期オブジェクトが名前空間に既に存在する場合は、既存の同期オブジェクトが使用されます。 別の型の同期オブジェクトが名前空間に既に存在する場合は、 WaitHandleCannotBeOpenedException がスローされます。 それ以外の場合は、新しい同期オブジェクトが作成されます。

が ではないnull場合name、呼び出しinitiallyOwned元スレッドはtrue、この呼び出しの結果として名前付きシステム ミューテックスが作成された場合にのみミューテックスを所有します。 名前付きシステム ミューテックスが作成されたかどうかを判断するメカニズムがないため、このコンストラクター オーバーロードを呼び出すときに を initiallyOwned 指定falseすることをお勧めします。 初期所有権を決定する Mutex(Boolean, String, Boolean) 必要がある場合は、 コンストラクターを使用できます。

このコンストラクターは、 Mutex 名前付きシステム ミューテックスを表す オブジェクトを初期化します。 同じ名前付きシステム ミューテックスを表す複数 Mutex のオブジェクトを作成できます。

アクセス制御セキュリティを使用して名前付きミューテックスが既に作成されており、呼び出し元に MutexRights.FullControlがない場合は、例外がスローされます。 スレッド アクティビティの同期に必要なアクセス許可のみを持つ既存の名前付きミューテックスを開くには、 メソッドを OpenExisting 参照してください。

または に空の文字列nameを指定nullすると、コンストラクターを呼び出したかのようにローカル ミューテックスがMutex(Boolean)作成されます。 この場合、 createdNew は常に trueです。

システム全体であるため、名前付きミューテックスを使用して、プロセス境界を越えてリソースの使用を調整できます。

Note

ターミナル サービスを実行しているサーバーでは、名前付きシステム ミューテックスに 2 つのレベルの可視性を設定できます。 名前が プレフィックス Global\で始まる場合、ミューテックスはすべてのターミナル サーバー セッションで表示されます。 名前が プレフィックス Local\で始まる場合、ミューテックスは作成されたターミナル サーバー セッションでのみ表示されます。 その場合、同じ名前の個別のミューテックスが、サーバー上の他の各ターミナル サーバー セッションに存在する可能性があります。 名前付きミューテックスを作成するときにプレフィックスを指定しない場合は、プレフィックス Local\を受け取ります。 ターミナル サーバー セッション内では、プレフィックスによってのみ名前が異なる 2 つのミューテックスは個別のミューテックスであり、両方ともターミナル サーバー セッション内のすべてのプロセスに表示されます。 つまり、プレフィックス名 Global\Local\ 、プロセスに対する相対ではなく、ターミナル サーバー セッションに対するミューテックス名のスコープを記述します。

注意事項

既定では、名前付きミューテックスは、それを作成したユーザーに制限されません。 他のユーザーは、ミューテックスを開いて使用できる場合があります。ミューテックスに入ってミューテックスを終了しないことによるミューテックスの干渉などです。 Unix に似たオペレーティング システムでは、ファイル システムは名前付きミューテックスの実装で使用され、他のユーザーは、より重要な方法で名前付きミューテックスに干渉できる可能性があります。 Windows では、特定のユーザーへのアクセスを制限するために、コンストラクター オーバーロードを使用するか MutexAcl 、名前付きミューテックスを作成するときに を渡 MutexSecurity すことができます。 Unix に似たオペレーティング システムでは、現在、名前付きミューテックスへのアクセスを制限する方法はありません。 信頼されていないユーザーがコードを実行している可能性があるシステムでは、アクセス制限なしで名前付きミューテックスを使用しないでください。

円記号 (\) は、ミューテックス名の予約文字です。 ターミナル サーバー セッションでのミューテックスの使用に関するメモで指定されている場合を除き、ミューテックス名に円記号 (\) を使用しないでください。 使用した場合、ミューテックスの名前が既存のファイルを表すとしても、DirectoryNotFoundException がスローされることがあります。

こちらもご覧ください

適用対象

Mutex(Boolean, String, Boolean)

Source:
Mutex.cs
Source:
Mutex.cs
Source:
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

このメソッドから制御が戻るとき、ローカル ミューテックスが作成された場合 (つまり namenull または空の文字列の場合) または指定した名前付きシステム ミューテックスが作成された場合は、ブール値 true が格納されます。指定した名前付きシステム ミューテックスが既に存在する場合は false が格納されます。 このパラメーターは初期化せずに渡されます。

属性

例外

名前付きミューテックスが存在し、それにアクセス制御セキュリティがありますが、ユーザーに FullControl がありません。

name が無効です。 これは、不明なプレフィックスや無効な文字など、オペレーティング システムによって配置される可能性のある制限など、さまざまな理由で発生する可能性があります。 名前と共通プレフィックス "Global\" と "Local\" では大文字と小文字が区別されることに注意してください。

または

他にもエラーが発生しました。 HResult プロパティにさらに情報が含まれている場合があります。

Windows のみ: name により不明な名前空間が指定されました。 詳しくは、「オブジェクト名」をご覧ください。

name は長すぎます。 長さの制限は、オペレーティング システムまたは構成によって異なる場合があります。

指定された name を持つ同期オブジェクトを作成できません。 別の型の同期オブジェクトに同じ名前が指定されている可能性があります。

.NET Frameworkのみ: name がMAX_PATH (260 文字) を超えています。

次のコード例は、プロセスまたはスレッド間でシグナルを通知するために名前付きミューテックスを使用する方法を示しています。 2 つ以上のコマンド ウィンドウからこのプログラムを実行します。 各プロセスは、 Mutex 名前付きミューテックス "MyMutex" を表す オブジェクトを作成します。 名前付きミューテックスはシステム オブジェクトです。 この例では、その有効期間は、それを表すオブジェクトの Mutex 有効期間によって制限されます。 名前付きミューテックスは、最初のプロセスがローカル Mutex オブジェクトを作成するときに作成され、それを表すすべての Mutex オブジェクトが解放されると破棄されます。 名前付きミューテックスは、最初のプロセスによって最初に所有されます。 2 番目のプロセスと後続のプロセスは、以前のプロセスが名前付きミューテックスを解放するまで待機します。

// 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 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 に似たオペレーティング システムでは、各シェルに独自のセッションがあります。 セッションローカル同期オブジェクトは、同じセッションで実行される親子関係を持つプロセス間の同期に適している場合があります。 Windows での同期オブジェクト名の詳細については、「 オブジェクト名」を参照してください。

nameが指定され、要求された型の同期オブジェクトが名前空間に既に存在する場合は、既存の同期オブジェクトが使用されます。 別の型の同期オブジェクトが名前空間に既に存在する場合は、 WaitHandleCannotBeOpenedException がスローされます。 それ以外の場合は、新しい同期オブジェクトが作成されます。

が で なくnullinitiallyOwned、 が の場合nametrue呼び出し元のスレッドは、 がtrue呼び出しの後にある場合createdNewにのみ、名前付きミューテックスを所有します。 それ以外の場合、スレッドは メソッドを呼び出すことによってミューテックスを WaitOne 要求できます。

このコンストラクターは、 Mutex 名前付きシステム ミューテックスを表す オブジェクトを初期化します。 同じ名前付きシステム ミューテックスを表す複数 Mutex のオブジェクトを作成できます。

名前付きミューテックスがアクセス制御セキュリティで既に作成されており、呼び出し元に権限がない MutexRights.FullControl 場合は、例外がスローされます。 スレッド アクティビティの同期に必要なアクセス許可のみを持つ既存の名前付きミューテックスを開くには、 メソッドを OpenExisting 参照してください。

または に空の文字列nameを指定nullすると、コンストラクターを呼び出した場合と同様に、ローカル ミューテックスがMutex(Boolean)作成されます。 この場合、 createdNew は常に trueです。

システム全体であるため、名前付きミューテックスを使用して、プロセス境界を越えてリソースの使用を調整できます。

Note

ターミナル サービスを実行しているサーバーでは、名前付きシステム ミューテックスに 2 つのレベルの可視性を設定できます。 名前が プレフィックス Global\で始まる場合、ミューテックスはすべてのターミナル サーバー セッションで表示されます。 名前が プレフィックス Local\で始まる場合、ミューテックスは作成されたターミナル サーバー セッションでのみ表示されます。 その場合は、サーバー上の他の各ターミナル サーバー セッションに、同じ名前の個別のミューテックスを存在させることができます。 名前付きミューテックスを作成するときにプレフィックスを指定しない場合は、プレフィックス Local\を受け取ります。 ターミナル サーバー セッション内では、プレフィックスによってのみ名前が異なる 2 つのミューテックスは個別のミューテックスであり、両方ともターミナル サーバー セッション内のすべてのプロセスに表示されます。 つまり、プレフィックス名 Global\Local\ 、プロセスに対する相対ではなく、ターミナル サーバー セッションに対するミューテックス名のスコープを記述します。

注意事項

既定では、名前付きミューテックスは、それを作成したユーザーに制限されません。 他のユーザーは、ミューテックスを開いて使用できる場合があります。ミューテックスに入ってミューテックスを終了しないことによるミューテックスの干渉などです。 Unix に似たオペレーティング システムでは、ファイル システムは名前付きミューテックスの実装で使用され、他のユーザーは、より重要な方法で名前付きミューテックスに干渉できる可能性があります。 Windows では、特定のユーザーへのアクセスを制限するために、コンストラクターのオーバーロードを使用するか MutexAcl 、名前付きミューテックスを作成するときに を渡すことができます MutexSecurity 。 Unix に似たオペレーティング システムでは、現在、名前付きミューテックスへのアクセスを制限する方法はありません。 信頼されていないユーザーがコードを実行している可能性があるシステムでは、アクセス制限なしで名前付きミューテックスを使用しないでください。

円記号 (\) はミューテックス名の予約文字です。 ターミナル サーバー セッションでのミューテックスの使用に関するメモで指定されている場合を除き、ミューテックス名に円記号 (\) を使用しないでください。 使用した場合、ミューテックスの名前が既存のファイルを表すとしても、DirectoryNotFoundException がスローされることがあります。

こちらもご覧ください

適用対象

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

このメソッドから制御が戻るとき、ローカル ミューテックスが作成された場合 (つまり namenull または空の文字列の場合) または指定した名前付きシステム ミューテックスが作成された場合は、ブール値 true が格納されます。指定した名前付きシステム ミューテックスが既に存在する場合は false が格納されます。 このパラメーターは初期化せずに渡されます。

mutexSecurity
MutexSecurity

名前付きシステム ミューテックスに適用するアクセス制御セキュリティを表す MutexSecurity オブジェクト。

属性

例外

name が無効です。 これは、不明なプレフィックスや無効な文字など、オペレーティング システムによって配置される可能性のある制限など、さまざまな理由で発生する可能性があります。 名前と共通プレフィックス "Global\" と "Local\" では大文字と小文字が区別されることに注意してください。

または

他にもエラーが発生しました。 HResult プロパティにさらに情報が含まれている場合があります。

Windows のみ: name により不明な名前空間が指定されました。 詳しくは、「オブジェクト名」をご覧ください。

name は長すぎます。 長さの制限は、オペレーティング システムまたは構成によって異なる場合があります。

名前付きミューテックスが存在し、それにアクセス制御セキュリティがありますが、ユーザーに FullControl がありません。

指定された name を持つ同期オブジェクトを作成できません。 別の型の同期オブジェクトに同じ名前が指定されている可能性があります。

.NET Frameworkのみ: name がMAX_PATH (260 文字) を超えています。

次のコード例は、アクセス制御セキュリティを備えた名前付きミューテックスのクロスプロセス動作を示しています。 この例では、 メソッドオーバーロードを OpenExisting(String) 使用して、名前付きミューテックスの存在をテストします。

ミューテックスが存在しない場合は、ミューテックスを使用する権限を現在のユーザーに拒否する初期所有権とアクセス制御セキュリティを使用して作成されますが、ミューテックスに対する読み取りと変更のアクセス許可を付与します。

2 つのコマンド ウィンドウからコンパイルされた例を実行した場合、2 番目のコピーは への OpenExisting(String)呼び出しでアクセス違反例外をスローします。 例外がキャッチされ、この例では メソッドオーバーロードを OpenExisting(String, MutexRights) 使用して、アクセス許可の読み取りと変更に必要な権限を持つミューテックスを開きます。

アクセス許可が変更されると、ミューテックスが開き、ミューテックスを入力して解放するために必要な権限が与えられます。 3 番目のコマンド ウィンドウからコンパイルされた例を実行すると、新しいアクセス許可を使用して実行されます。

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;
            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 に似たオペレーティング システムでは、各シェルに独自のセッションがあります。 セッションとローカルの同期オブジェクトは、プロセス間の同期に適している場合があります。これらはすべて同じセッションで実行される親子関係を持ちます。 Windows での同期オブジェクト名の詳細については、「 オブジェクト名」を参照してください。

nameが指定され、要求された型の同期オブジェクトが名前空間に既に存在する場合は、既存の同期オブジェクトが使用されます。 別の型の同期オブジェクトが名前空間に既に存在する場合は、 WaitHandleCannotBeOpenedException がスローされます。 それ以外の場合は、新しい同期オブジェクトが作成されます。

が でなくnullinitiallyOwned、 が のtrue場合name、呼び出し元のスレッドは、 がtrue呼び出しの後にある場合createdNewにのみ、名前付きミューテックスを所有します。 それ以外の場合、スレッドは メソッドを呼び出してミューテックスを WaitOne 要求できます。

このコンストラクターを使用して、名前付きシステム ミューテックスの作成時にアクセス制御セキュリティを適用し、他のコードがミューテックスを制御できないようにします。

このコンストラクターは、 Mutex 名前付きシステム ミューテックスを表す オブジェクトを初期化します。 同じ名前付きシステム ミューテックスを表す複数 Mutex のオブジェクトを作成できます。

名前付きシステム ミューテックスが存在しない場合は、指定されたアクセス制御セキュリティを使用して作成されます。 名前付きミューテックスが存在する場合、指定されたアクセス制御セキュリティは無視されます。

Note

呼び出し元は、現在のユーザーにアクセス権を拒否または許可できない場合mutexSecurityでも、新しく作成Mutexされたオブジェクトを完全に制御できます。 ただし、現在のユーザーがコンストラクターまたは メソッドを使用して、同じ名前付きミューテックスを表す別 Mutex のオブジェクトを OpenExisting 取得しようとすると、Windows アクセス制御セキュリティが適用されます。

アクセス制御セキュリティを使用して名前付きミューテックスが既に作成されており、呼び出し元に MutexRights.FullControlがない場合は、例外がスローされます。 スレッド アクティビティの同期に必要なアクセス許可のみを持つ既存の名前付きミューテックスを開くには、 メソッドを OpenExisting 参照してください。

または に空の文字列nameを指定nullすると、コンストラクターを呼び出したかのようにローカル ミューテックスがMutex(Boolean)作成されます。 この場合、 createdNew は常に trueです。

システム全体であるため、名前付きミューテックスを使用して、プロセス境界を越えてリソースの使用を調整できます。

Note

ターミナル サービスを実行しているサーバーでは、名前付きシステム ミューテックスに 2 つのレベルの可視性を設定できます。 名前が プレフィックス Global\で始まる場合、ミューテックスはすべてのターミナル サーバー セッションで表示されます。 名前が プレフィックス Local\で始まる場合、ミューテックスは作成されたターミナル サーバー セッションでのみ表示されます。 その場合、同じ名前の個別のミューテックスが、サーバー上の他の各ターミナル サーバー セッションに存在する可能性があります。 名前付きミューテックスを作成するときにプレフィックスを指定しない場合は、プレフィックス Local\を受け取ります。 ターミナル サーバー セッション内では、プレフィックスによってのみ名前が異なる 2 つのミューテックスは個別のミューテックスであり、両方ともターミナル サーバー セッション内のすべてのプロセスに表示されます。 つまり、プレフィックス名 Global\Local\ 、プロセスに対する相対ではなく、ターミナル サーバー セッションに対するミューテックス名のスコープを記述します。

注意事項

既定では、名前付きミューテックスは、それを作成したユーザーに制限されません。 他のユーザーは、ミューテックスを開いて使用できる場合があります。ミューテックスに入ってミューテックスを終了しないことによるミューテックスの干渉などです。 特定のユーザーへのアクセスを制限するために、名前付きミューテックスを作成するときに を渡 MutexSecurity すことができます。 信頼されていないユーザーがコードを実行している可能性があるシステムでは、アクセス制限なしで名前付きミューテックスを使用しないでください。

円記号 (\) は、ミューテックス名の予約文字です。 ターミナル サーバー セッションでのミューテックスの使用に関するメモで指定されている場合を除き、ミューテックス名に円記号 (\) を使用しないでください。 使用した場合、ミューテックスの名前が既存のファイルを表すとしても、DirectoryNotFoundException がスローされることがあります。

適用対象