Semaphore.OpenExisting メソッド

定義

既に存在する場合は、指定した名前付きセマフォを開きます。

オーバーロード

名前 説明
OpenExisting(String)

指定した名前付きセマフォが既に存在する場合は開きます。

OpenExisting(String, SemaphoreRights)

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

OpenExisting(String, NamedWaitHandleOptions)

指定した名前付きセマフォが既に存在する場合は開きます。 オプションが現在のユーザーのみに設定されている場合、オブジェクトのアクセス制御は呼び出し元のユーザーに対して検証されます。

OpenExisting(String)

ソース:
Semaphore.cs
ソース:
Semaphore.cs
ソース:
Semaphore.cs
ソース:
Semaphore.cs
ソース:
Semaphore.cs

指定した名前付きセマフォが既に存在する場合は開きます。

public:
 static System::Threading::Semaphore ^ OpenExisting(System::String ^ name);
public static System.Threading.Semaphore OpenExisting(string name);
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
public static System.Threading.Semaphore OpenExisting(string name);
static member OpenExisting : string -> System.Threading.Semaphore
[<System.Runtime.Versioning.SupportedOSPlatform("windows")>]
static member OpenExisting : string -> System.Threading.Semaphore
Public Shared Function OpenExisting (name As String) As Semaphore

パラメーター

name
String

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

返品

名前付きシステム セマフォを表すオブジェクト。

属性

例外

name は空の文字列です。

-又は-

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

namenullです。

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

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

-又は-

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

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

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

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

セマフォが存在しない場合、セマフォは最大カウント 2 で作成され、アクセス制御セキュリティにより、現在のユーザーはセマフォを使用する権限を拒否しますが、セマフォに対するアクセス許可の読み取りと変更の権限が付与されます。

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

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

using System;
using System.Threading;
using System.Security.AccessControl;

internal class Example
{
    internal static void Main()
    {
        const string semaphoreName = "SemaphoreExample5";

        Semaphore sem = null;
        bool doesNotExist = false;
        bool unauthorized = false;

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

        // There are three cases: (1) The semaphore does not exist.
        // (2) The semaphore exists, but the current user doesn't 
        // have access. (3) The semaphore exists and the user has
        // access.
        //
        if (doesNotExist)
        {
            // The semaphore does not exist, so create it.
            //
            // The value of this variable is set by the semaphore
            // constructor. It is true if the named system semaphore was
            // created, and false if the named semaphore already existed.
            //
            bool semaphoreWasCreated;

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

            SemaphoreAccessRule rule = new SemaphoreAccessRule(
                user, 
                SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                AccessControlType.Deny);
            semSec.AddAccessRule(rule);

            rule = new SemaphoreAccessRule(
                user, 
                SemaphoreRights.ReadPermissions | SemaphoreRights.ChangePermissions,
                AccessControlType.Allow);
            semSec.AddAccessRule(rule);

            // Create a Semaphore object that represents the system
            // semaphore named by the constant 'semaphoreName', with
            // maximum count three, initial count three, and the
            // specified security access. The Boolean value that 
            // indicates creation of the underlying system object is
            // placed in semaphoreWasCreated.
            //
            sem = new Semaphore(3, 3, semaphoreName, 
                out semaphoreWasCreated, semSec);

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

                // Get the current ACL. This requires 
                // SemaphoreRights.ReadPermissions.
                SemaphoreSecurity semSec = sem.GetAccessControl();
                
                string user = Environment.UserDomainName + "\\" 
                    + Environment.UserName;

                // First, the rule that denied the current user 
                // the right to enter and release the semaphore must
                // be removed.
                SemaphoreAccessRule rule = new SemaphoreAccessRule(
                    user, 
                    SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                    AccessControlType.Deny);
                semSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new SemaphoreAccessRule(user, 
                     SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                     AccessControlType.Allow);
                semSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // SemaphoreRights.ChangePermissions.
                sem.SetAccessControl(semSec);

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

                // Open the semaphore with (SemaphoreRights.Synchronize 
                // | SemaphoreRights.Modify), the rights required to
                // enter and release the semaphore.
                //
                sem = Semaphore.OpenExisting(semaphoreName);
            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}", ex.Message);
                return;
            }
        }

        // Enter the semaphore, and hold it until the program
        // exits.
        //
        try
        {
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore.");
            Console.WriteLine("Press the Enter key to exit.");
            Console.ReadLine();
            sem.Release();
        }
        catch(UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
        }
    }
}
Imports System.Threading
Imports System.Security.AccessControl

Friend Class Example

    <MTAThread> _
    Friend Shared Sub Main()
        Const semaphoreName As String = "SemaphoreExample5"

        Dim sem As Semaphore = Nothing
        Dim doesNotExist as Boolean = False
        Dim unauthorized As Boolean = False

        ' Attempt to open the named semaphore.
        Try
            ' Open the semaphore with (SemaphoreRights.Synchronize
            ' Or SemaphoreRights.Modify), to enter and release the
            ' named semaphore.
            '
            sem = Semaphore.OpenExisting(semaphoreName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Semaphore 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 semaphore does not exist.
        ' (2) The semaphore exists, but the current user doesn't 
        ' have access. (3) The semaphore exists and the user has
        ' access.
        '
        If doesNotExist Then
            ' The semaphore does not exist, so create it.
            '
            ' The value of this variable is set by the semaphore
            ' constructor. It is True if the named system semaphore was
            ' created, and False if the named semaphore already existed.
            '
            Dim semaphoreWasCreated As Boolean

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

            Dim rule As New SemaphoreAccessRule(user, _
                SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
                AccessControlType.Deny)
            semSec.AddAccessRule(rule)

            rule = New SemaphoreAccessRule(user, _
                SemaphoreRights.ReadPermissions Or _
                SemaphoreRights.ChangePermissions, _
                AccessControlType.Allow)
            semSec.AddAccessRule(rule)

            ' Create a Semaphore object that represents the system
            ' semaphore named by the constant 'semaphoreName', with
            ' maximum count three, initial count three, and the
            ' specified security access. The Boolean value that 
            ' indicates creation of the underlying system object is
            ' placed in semaphoreWasCreated.
            '
            sem = New Semaphore(3, 3, semaphoreName, _
                semaphoreWasCreated, semSec)

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

        ElseIf unauthorized Then

            ' Open the semaphore to read and change the access
            ' control security. The access control security defined
            ' above allows the current user to do this.
            '
            Try
                sem = Semaphore.OpenExisting(semaphoreName, _
                    SemaphoreRights.ReadPermissions Or _
                    SemaphoreRights.ChangePermissions)

                ' Get the current ACL. This requires 
                ' SemaphoreRights.ReadPermissions.
                Dim semSec As SemaphoreSecurity = sem.GetAccessControl()
                
                Dim user As String = Environment.UserDomainName _ 
                    & "\" & Environment.UserName

                ' First, the rule that denied the current user 
                ' the right to enter and release the semaphore must
                ' be removed.
                Dim rule As New SemaphoreAccessRule(user, _
                    SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
                    AccessControlType.Deny)
                semSec.RemoveAccessRule(rule)

                ' Now grant the user the correct rights.
                ' 
                rule = New SemaphoreAccessRule(user, _
                    SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
                    AccessControlType.Allow)
                semSec.AddAccessRule(rule)

                ' Update the ACL. This requires
                ' SemaphoreRights.ChangePermissions.
                sem.SetAccessControl(semSec)

                Console.WriteLine("Updated semaphore security.")

                ' Open the semaphore with (SemaphoreRights.Synchronize 
                ' Or SemaphoreRights.Modify), the rights required to
                ' enter and release the semaphore.
                '
                sem = Semaphore.OpenExisting(semaphoreName)

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

        End If

        ' Enter the semaphore, and hold it until the program
        ' exits.
        '
        Try
            sem.WaitOne()
            Console.WriteLine("Entered the semaphore.")
            Console.WriteLine("Press the Enter key to exit.")
            Console.ReadLine()
            sem.Release()
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", _
                ex.Message)
        End Try
    End Sub 
End Class

注釈

nameには、名前空間を指定するために、Global\またはLocal\のプレフィックスを付ける場合があります。 Global名前空間を指定すると、同期オブジェクトをシステム上の任意のプロセスと共有できます。 Local名前空間が指定されている場合(名前空間が指定されていない場合の既定値)、同期オブジェクトを同じセッション内のプロセスと共有できます。 Windowsでは、セッションはログイン セッションであり、サービスは通常、別の非対話型セッションで実行されます。 Unix に似たオペレーティング システムでは、各シェルに独自のセッションがあります。 セッションとローカルの同期オブジェクトは、プロセス間の同期に適している場合があります。このオブジェクトはすべて同じセッションで実行されます。 Windowsの同期オブジェクト名の詳細については、「Object Names」を参照してください。

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

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

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

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

SemaphoreRights.Synchronize フラグを指定すると、スレッドはセマフォに入ることができます。また、SemaphoreRights.Modify フラグを指定すると、スレッドは Release メソッドを呼び出すことができます。

こちらもご覧ください

適用対象

OpenExisting(String, SemaphoreRights)

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

public:
 static System::Threading::Semaphore ^ OpenExisting(System::String ^ name, System::Security::AccessControl::SemaphoreRights rights);
public static System.Threading.Semaphore OpenExisting(string name, System.Security.AccessControl.SemaphoreRights rights);
static member OpenExisting : string * System.Security.AccessControl.SemaphoreRights -> System.Threading.Semaphore
Public Shared Function OpenExisting (name As String, rights As SemaphoreRights) As Semaphore

パラメーター

name
String

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

rights
SemaphoreRights

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

返品

名前付きシステム セマフォを表すオブジェクト。

例外

name は空の文字列です。

-又は-

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

namenullです。

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

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

-又は-

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

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

名前付きセマフォは存在しますが、ユーザーには必要なセキュリティ アクセス権がありません。

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

セマフォが存在しない場合、セマフォは最大カウント 2 で作成され、アクセス制御セキュリティにより、現在のユーザーはセマフォを使用する権限を拒否しますが、セマフォに対するアクセス許可の読み取りと変更の権限を付与します。

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

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

using System;
using System.Threading;
using System.Security.AccessControl;

internal class Example
{
    internal static void Main()
    {
        const string semaphoreName = "SemaphoreExample5";

        Semaphore sem = null;
        bool doesNotExist = false;
        bool unauthorized = false;

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

        // There are three cases: (1) The semaphore does not exist.
        // (2) The semaphore exists, but the current user doesn't 
        // have access. (3) The semaphore exists and the user has
        // access.
        //
        if (doesNotExist)
        {
            // The semaphore does not exist, so create it.
            //
            // The value of this variable is set by the semaphore
            // constructor. It is true if the named system semaphore was
            // created, and false if the named semaphore already existed.
            //
            bool semaphoreWasCreated;

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

            SemaphoreAccessRule rule = new SemaphoreAccessRule(
                user, 
                SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                AccessControlType.Deny);
            semSec.AddAccessRule(rule);

            rule = new SemaphoreAccessRule(
                user, 
                SemaphoreRights.ReadPermissions | SemaphoreRights.ChangePermissions,
                AccessControlType.Allow);
            semSec.AddAccessRule(rule);

            // Create a Semaphore object that represents the system
            // semaphore named by the constant 'semaphoreName', with
            // maximum count three, initial count three, and the
            // specified security access. The Boolean value that 
            // indicates creation of the underlying system object is
            // placed in semaphoreWasCreated.
            //
            sem = new Semaphore(3, 3, semaphoreName, 
                out semaphoreWasCreated, semSec);

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

                // Get the current ACL. This requires 
                // SemaphoreRights.ReadPermissions.
                SemaphoreSecurity semSec = sem.GetAccessControl();
                
                string user = Environment.UserDomainName + "\\" 
                    + Environment.UserName;

                // First, the rule that denied the current user 
                // the right to enter and release the semaphore must
                // be removed.
                SemaphoreAccessRule rule = new SemaphoreAccessRule(
                    user, 
                    SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                    AccessControlType.Deny);
                semSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new SemaphoreAccessRule(user, 
                     SemaphoreRights.Synchronize | SemaphoreRights.Modify, 
                     AccessControlType.Allow);
                semSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // SemaphoreRights.ChangePermissions.
                sem.SetAccessControl(semSec);

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

                // Open the semaphore with (SemaphoreRights.Synchronize 
                // | SemaphoreRights.Modify), the rights required to
                // enter and release the semaphore.
                //
                sem = Semaphore.OpenExisting(semaphoreName);
            }
            catch(UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}", ex.Message);
                return;
            }
        }

        // Enter the semaphore, and hold it until the program
        // exits.
        //
        try
        {
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore.");
            Console.WriteLine("Press the Enter key to exit.");
            Console.ReadLine();
            sem.Release();
        }
        catch(UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
        }
    }
}
Imports System.Threading
Imports System.Security.AccessControl

Friend Class Example

    <MTAThread> _
    Friend Shared Sub Main()
        Const semaphoreName As String = "SemaphoreExample5"

        Dim sem As Semaphore = Nothing
        Dim doesNotExist as Boolean = False
        Dim unauthorized As Boolean = False

        ' Attempt to open the named semaphore.
        Try
            ' Open the semaphore with (SemaphoreRights.Synchronize
            ' Or SemaphoreRights.Modify), to enter and release the
            ' named semaphore.
            '
            sem = Semaphore.OpenExisting(semaphoreName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Semaphore 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 semaphore does not exist.
        ' (2) The semaphore exists, but the current user doesn't 
        ' have access. (3) The semaphore exists and the user has
        ' access.
        '
        If doesNotExist Then
            ' The semaphore does not exist, so create it.
            '
            ' The value of this variable is set by the semaphore
            ' constructor. It is True if the named system semaphore was
            ' created, and False if the named semaphore already existed.
            '
            Dim semaphoreWasCreated As Boolean

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

            Dim rule As New SemaphoreAccessRule(user, _
                SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
                AccessControlType.Deny)
            semSec.AddAccessRule(rule)

            rule = New SemaphoreAccessRule(user, _
                SemaphoreRights.ReadPermissions Or _
                SemaphoreRights.ChangePermissions, _
                AccessControlType.Allow)
            semSec.AddAccessRule(rule)

            ' Create a Semaphore object that represents the system
            ' semaphore named by the constant 'semaphoreName', with
            ' maximum count three, initial count three, and the
            ' specified security access. The Boolean value that 
            ' indicates creation of the underlying system object is
            ' placed in semaphoreWasCreated.
            '
            sem = New Semaphore(3, 3, semaphoreName, _
                semaphoreWasCreated, semSec)

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

        ElseIf unauthorized Then

            ' Open the semaphore to read and change the access
            ' control security. The access control security defined
            ' above allows the current user to do this.
            '
            Try
                sem = Semaphore.OpenExisting(semaphoreName, _
                    SemaphoreRights.ReadPermissions Or _
                    SemaphoreRights.ChangePermissions)

                ' Get the current ACL. This requires 
                ' SemaphoreRights.ReadPermissions.
                Dim semSec As SemaphoreSecurity = sem.GetAccessControl()
                
                Dim user As String = Environment.UserDomainName _ 
                    & "\" & Environment.UserName

                ' First, the rule that denied the current user 
                ' the right to enter and release the semaphore must
                ' be removed.
                Dim rule As New SemaphoreAccessRule(user, _
                    SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
                    AccessControlType.Deny)
                semSec.RemoveAccessRule(rule)

                ' Now grant the user the correct rights.
                ' 
                rule = New SemaphoreAccessRule(user, _
                    SemaphoreRights.Synchronize Or SemaphoreRights.Modify, _
                    AccessControlType.Allow)
                semSec.AddAccessRule(rule)

                ' Update the ACL. This requires
                ' SemaphoreRights.ChangePermissions.
                sem.SetAccessControl(semSec)

                Console.WriteLine("Updated semaphore security.")

                ' Open the semaphore with (SemaphoreRights.Synchronize 
                ' Or SemaphoreRights.Modify), the rights required to
                ' enter and release the semaphore.
                '
                sem = Semaphore.OpenExisting(semaphoreName)

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

        End If

        ' Enter the semaphore, and hold it until the program
        ' exits.
        '
        Try
            sem.WaitOne()
            Console.WriteLine("Entered the semaphore.")
            Console.WriteLine("Press the Enter key to exit.")
            Console.ReadLine()
            sem.Release()
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", _
                ex.Message)
        End Try
    End Sub 
End Class

注釈

nameには、名前空間を指定するために、Global\またはLocal\のプレフィックスを付ける場合があります。 Global名前空間を指定すると、同期オブジェクトをシステム上の任意のプロセスと共有できます。 Local名前空間が指定されている場合(名前空間が指定されていない場合の既定値)、同期オブジェクトを同じセッション内のプロセスと共有できます。 Windowsでは、セッションはログイン セッションであり、サービスは通常、別の非対話型セッションで実行されます。 Unix に似たオペレーティング システムでは、各シェルに独自のセッションがあります。 セッションとローカルの同期オブジェクトは、プロセス間の同期に適している場合があります。このオブジェクトはすべて同じセッションで実行されます。 Windowsの同期オブジェクト名の詳細については、「Object Names」を参照してください。

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

rights パラメーターには、スレッドがセマフォに入ることができるようにSemaphoreRights.Synchronize フラグと、スレッドが Release メソッドを呼び出すことができるようにするSemaphoreRights.Modify フラグを含める必要があります。

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

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

こちらもご覧ください

適用対象

OpenExisting(String, NamedWaitHandleOptions)

ソース:
Semaphore.cs
ソース:
Semaphore.cs

指定した名前付きセマフォが既に存在する場合は開きます。 オプションが現在のユーザーのみに設定されている場合、オブジェクトのアクセス制御は呼び出し元のユーザーに対して検証されます。

public:
 static System::Threading::Semaphore ^ OpenExisting(System::String ^ name, System::Threading::NamedWaitHandleOptions options);
[System.Runtime.Versioning.SupportedOSPlatform("windows")]
public static System.Threading.Semaphore OpenExisting(string name, System.Threading.NamedWaitHandleOptions options);
[<System.Runtime.Versioning.SupportedOSPlatform("windows")>]
static member OpenExisting : string * System.Threading.NamedWaitHandleOptions -> System.Threading.Semaphore
Public Shared Function OpenExisting (name As String, options As NamedWaitHandleOptions) As Semaphore

パラメーター

name
String

他のプロセスと共有する同期オブジェクトの名前。 名前では大文字と小文字が区別されます。 円記号 (\) は予約されており、名前空間の指定にのみ使用できます。 名前空間の詳細については、「解説」セクションを参照してください。

options
NamedWaitHandleOptions

名前付きセマフォのスコープ オプション。 既定では、アクセスは現在のユーザーと現在のセッションのみに制限されます。 指定したオプションは、名前の名前空間と、基になるセマフォ オブジェクトへのアクセスに影響する可能性があります。

返品

名前付きシステム セマフォを表すオブジェクト。

属性

例外

name は空の文字列です。

namenullです。

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

-又は-

指定した name を持つオブジェクトが存在しますが、指定した options は既存のオブジェクトのオプションと互換性がありません。

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

-又は-

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

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

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

注釈

要求された型の同期オブジェクトが名前空間に存在する場合は、既存の同期オブジェクトが開かれます。 ただし、 options が現在のユーザーに限定されたアクセスを指定し、同期オブジェクトと互換性がない場合は、 WaitHandleCannotBeOpenedException がスローされます。 同期オブジェクトが名前空間に存在しない場合、または別の型の同期オブジェクトが名前空間に存在する場合は、 WaitHandleCannotBeOpenedException もスローされます。

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

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

こちらもご覧ください

適用対象