Mutex.OpenExisting メソッド

定義

既に存在する場合は、指定した名前付きミューテックスを開きます。

オーバーロード

名前 説明
OpenExisting(String)

指定した名前付きミューテックスが既に存在する場合は、それを開きます。

OpenExisting(String, MutexRights)

指定した名前付きミューテックスが既に存在する場合は、目的のセキュリティ アクセスを使用して開きます。

OpenExisting(String)

指定した名前付きミューテックスが既に存在する場合は、それを開きます。

public:
 static System::Threading::Mutex ^ OpenExisting(System::String ^ name);
[System.Security.SecurityCritical]
public static System.Threading.Mutex OpenExisting(string name);
public static System.Threading.Mutex OpenExisting(string name);
[<System.Security.SecurityCritical>]
static member OpenExisting : string -> System.Threading.Mutex
static member OpenExisting : string -> System.Threading.Mutex
Public Shared Function OpenExisting (name As String) As Mutex

パラメーター

name
String

他のプロセスと共有する同期オブジェクトの名前。 名前では大文字と小文字が区別されます。 円記号 (\) は予約されており、名前空間の指定にのみ使用できます。 名前空間の詳細については、「解説」セクションを参照してください。 オペレーティング システムによっては、名前にさらに制限がある場合があります。 たとえば、Unix ベースのオペレーティング システムでは、名前空間を除外した後の名前は有効なファイル名である必要があります。

返品

名前付きシステム ミューテックスを表すオブジェクト。

属性

例外

name は空の文字列です。

-または-

.NET Framework のみ: name がMAX_PATH (260 文字) より長くなっています。

namenullです。

指定された name を持つ同期オブジェクトを作成できません。 異なる種類の同期オブジェクトの名前が同じである可能性があります。 場合によっては、無効な名前に対してこの例外がスローされることがあります。

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

-または-

その他のエラーが発生しました。 HResultプロパティは、詳細情報を提供する場合があります。

Windowsのみ: nameが不明な名前空間を指定しました。 詳細については、「 オブジェクト名」 を参照してください。

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

名前付きミューテックスは存在しますが、ユーザーはミューテックスを使用するために必要なセキュリティ アクセス権を持っていません。

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

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

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

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

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の同期オブジェクト名の詳細については、「Object Names」を参照してください。

要求された型の同期オブジェクトが名前空間に存在する場合は、既存の同期オブジェクトが開かれます。 同期オブジェクトが名前空間に存在しない場合、または別の型の同期オブジェクトが名前空間に存在する場合は、 WaitHandleCannotBeOpenedException がスローされます。

OpenExisting メソッドは、指定した名前付きシステム ミューテックスを開こうとします。 システム ミューテックスがまだ存在しない場合に作成するには、name パラメーターを持つ Mutex コンストラクターのいずれかを使用します。

nameに同じ値を使用するこのメソッドを複数回呼び出しても、返されるオブジェクトが同じ名前付きシステム ミューテックスを表していても、必ずしも同じMutex オブジェクトを返すわけではありません。

このメソッド オーバーロードは、 OpenExisting(String, MutexRights) メソッドオーバーロードを呼び出し、ビットごとの OR 演算を使用して結合された MutexRights.Synchronize 権限と MutexRights.Modify 権限を指定することと同じです。

MutexRights.Synchronize フラグを指定すると、スレッドはミューテックスを待機でき、MutexRights.Modify フラグを指定すると、スレッドは ReleaseMutex メソッドを呼び出すことができます。

このメソッドはミューテックスの所有権を要求しません。

適用対象

OpenExisting(String, MutexRights)

指定した名前付きミューテックスが既に存在する場合は、目的のセキュリティ アクセスを使用して開きます。

public:
 static System::Threading::Mutex ^ OpenExisting(System::String ^ name, System::Security::AccessControl::MutexRights rights);
public static System.Threading.Mutex OpenExisting(string name, System.Security.AccessControl.MutexRights rights);
[System.Security.SecurityCritical]
public static System.Threading.Mutex OpenExisting(string name, System.Security.AccessControl.MutexRights rights);
static member OpenExisting : string * System.Security.AccessControl.MutexRights -> System.Threading.Mutex
[<System.Security.SecurityCritical>]
static member OpenExisting : string * System.Security.AccessControl.MutexRights -> System.Threading.Mutex
Public Shared Function OpenExisting (name As String, rights As MutexRights) As Mutex

パラメーター

name
String

他のプロセスと共有する同期オブジェクトの名前。 名前では大文字と小文字が区別されます。 円記号 (\) は予約されており、名前空間の指定にのみ使用できます。 名前空間の詳細については、「解説」セクションを参照してください。 オペレーティング システムによっては、名前にさらに制限がある場合があります。 たとえば、Unix ベースのオペレーティング システムでは、名前空間を除外した後の名前は有効なファイル名である必要があります。

rights
MutexRights

目的のセキュリティ アクセスを表す列挙値のビットごとの組み合わせ。

返品

名前付きシステム ミューテックスを表すオブジェクト。

属性

例外

name は空の文字列です。

-または-

.NET Framework のみ: name がMAX_PATH (260 文字) より長くなっています。

namenullです。

指定された name を持つ同期オブジェクトを作成できません。 異なる種類の同期オブジェクトの名前が同じである可能性があります。 場合によっては、無効な名前に対してこの例外がスローされることがあります。

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

-または-

その他のエラーが発生しました。 HResultプロパティは、詳細情報を提供する場合があります。

Windowsのみ: nameが不明な名前空間を指定しました。 詳細については、「 オブジェクト名」 を参照してください。

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

名前付きミューテックスは存在しますが、ユーザーは目的のセキュリティ アクセス権を持っていません。

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

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

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

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

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の同期オブジェクト名の詳細については、「Object Names」を参照してください。

要求された型の同期オブジェクトが名前空間に存在する場合は、既存の同期オブジェクトが開かれます。 同期オブジェクトが名前空間に存在しない場合、または別の型の同期オブジェクトが名前空間に存在する場合は、 WaitHandleCannotBeOpenedException がスローされます。

rights パラメーターには、スレッドがミューテックスを待機できるようにするための MutexRights.Synchronize フラグと、スレッドが ReleaseMutex メソッドを呼び出すことができるようにする MutexRights.Modify フラグを含める必要があります。

OpenExisting メソッドは、既存の名前付きミューテックスを開こうとします。 システム ミューテックスがまだ存在しない場合に作成するには、name パラメーターを持つ Mutex コンストラクターのいずれかを使用します。

nameに同じ値を使用するこのメソッドを複数回呼び出しても、返されるオブジェクトが同じ名前付きシステム ミューテックスを表していても、必ずしも同じMutex オブジェクトを返すわけではありません。

このメソッドはミューテックスの所有権を要求しません。

適用対象