Semaphore コンストラクター

定義

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

オーバーロード

Semaphore(Int32, Int32)

エントリ数の初期値と同時実行エントリの最大数を指定して、Semaphore クラスの新しいインスタンスを初期化します。

Semaphore(Int32, Int32, String)

エントリ数の初期値と同時実行エントリの最大数を指定し、オプションでシステム セマフォ オブジェクトの名前を指定して、Semaphore クラスの新しいインスタンスを初期化します。

Semaphore(Int32, Int32, String, Boolean)

エントリ数の初期値と同時実行エントリの最大数を指定し、オプションでシステム セマフォ オブジェクトの名前を指定し、新しいシステム セマフォが作成されたかどうかを示す値を受け取る変数を指定して、Semaphore クラスの新しいインスタンスを初期化します。

Semaphore(Int32, Int32, String, Boolean, SemaphoreSecurity)

エントリ数の初期値と同時実行エントリの最大数を指定し、オプションでシステム セマフォ オブジェクトの名前を指定し、新しいシステム セマフォが作成されたかどうかを示す値を受け取る変数を指定し、システム セマフォのセキュリティ アクセス制御を指定して、Semaphore クラスの新しいインスタンスを初期化します。

Semaphore(Int32, Int32)

エントリ数の初期値と同時実行エントリの最大数を指定して、Semaphore クラスの新しいインスタンスを初期化します。

public:
 Semaphore(int initialCount, int maximumCount);
public Semaphore (int initialCount, int maximumCount);
new System.Threading.Semaphore : int * int -> System.Threading.Semaphore
Public Sub New (initialCount As Integer, maximumCount As Integer)

パラメーター

initialCount
Int32

同時に許可されるセマフォの要求の初期数。

maximumCount
Int32

同時に許可されるセマフォの要求の最大数。

例外

initialCountmaximumCount より大きくなっています。

maximumCount が 1 未満です。

または

initialCount が 0 未満です。

次の例では、最大カウントが 3 で、初期カウントが 0 のセマフォを作成します。 この例では、セマフォの待機をブロックする 5 つのスレッドを開始します。 メイン スレッドは、メソッド オーバーロードをRelease(Int32)使用してセマフォ数を最大値に増やし、3 つのスレッドがセマフォに入れるようにします。 各スレッドは、 メソッドを Thread.Sleep 使用して 1 秒間待機し、作業をシミュレートしてから、メソッド オーバーロードを Release() 呼び出してセマフォを解放します。 セマフォが解放されるたびに、前のセマフォ数が表示されます。 コンソール メッセージはセマフォの使用を追跡します。 シミュレートされた作業間隔は、スレッドごとに若干増加し、出力を読みやすくします。

#using <System.dll>
using namespace System;
using namespace System::Threading;

public ref class Example
{
private:
   // A semaphore that simulates a limited resource pool.
   //
   static Semaphore^ _pool;

   // A padding interval to make the output more orderly.
   static int _padding;

public:
   static void Main()
   {
      // Create a semaphore that can satisfy up to three
      // concurrent requests. Use an initial count of zero,
      // so that the entire semaphore count is initially
      // owned by the main program thread.
      //
      _pool = gcnew Semaphore( 0,3 );
      
      // Create and start five numbered threads.
      //
      for ( int i = 1; i <= 5; i++ )
      {
         Thread^ t = gcnew Thread(
            gcnew ParameterizedThreadStart( Worker ) );
         
         // Start the thread, passing the number.
         //
         t->Start( i );
      }
      
      // Wait for half a second, to allow all the
      // threads to start and to block on the semaphore.
      //
      Thread::Sleep( 500 );
      
      // The main thread starts out holding the entire
      // semaphore count. Calling Release(3) brings the
      // semaphore count back to its maximum value, and
      // allows the waiting threads to enter the semaphore,
      // up to three at a time.
      //
      Console::WriteLine( L"Main thread calls Release(3)." );
      _pool->Release( 3 );

      Console::WriteLine( L"Main thread exits." );
   }

private:
   static void Worker( Object^ num )
   {
      // Each worker thread begins by requesting the
      // semaphore.
      Console::WriteLine( L"Thread {0} begins and waits for the semaphore.", num );
      _pool->WaitOne();
      
      // A padding interval to make the output more orderly.
      int padding = Interlocked::Add( _padding, 100 );

      Console::WriteLine( L"Thread {0} enters the semaphore.", num );
      
      // The thread's "work" consists of sleeping for
      // about a second. Each thread "works" a little
      // longer, just to make the output more orderly.
      //
      Thread::Sleep( 1000 + padding );

      Console::WriteLine( L"Thread {0} releases the semaphore.", num );
      Console::WriteLine( L"Thread {0} previous semaphore count: {1}",
         num, _pool->Release() );
   }
};
using System;
using System.Threading;

public class Example
{
    // A semaphore that simulates a limited resource pool.
    //
    private static Semaphore _pool;

    // A padding interval to make the output more orderly.
    private static int _padding;

    public static void Main()
    {
        // Create a semaphore that can satisfy up to three
        // concurrent requests. Use an initial count of zero,
        // so that the entire semaphore count is initially
        // owned by the main program thread.
        //
        _pool = new Semaphore(initialCount: 0, maximumCount: 3);

        // Create and start five numbered threads. 
        //
        for(int i = 1; i <= 5; i++)
        {
            Thread t = new Thread(new ParameterizedThreadStart(Worker));

            // Start the thread, passing the number.
            //
            t.Start(i);
        }

        // Wait for half a second, to allow all the
        // threads to start and to block on the semaphore.
        //
        Thread.Sleep(500);

        // The main thread starts out holding the entire
        // semaphore count. Calling Release(3) brings the 
        // semaphore count back to its maximum value, and
        // allows the waiting threads to enter the semaphore,
        // up to three at a time.
        //
        Console.WriteLine("Main thread calls Release(3).");
        _pool.Release(releaseCount: 3);

        Console.WriteLine("Main thread exits.");
    }

    private static void Worker(object num)
    {
        // Each worker thread begins by requesting the
        // semaphore.
        Console.WriteLine("Thread {0} begins " +
            "and waits for the semaphore.", num);
        _pool.WaitOne();

        // A padding interval to make the output more orderly.
        int padding = Interlocked.Add(ref _padding, 100);

        Console.WriteLine("Thread {0} enters the semaphore.", num);
        
        // The thread's "work" consists of sleeping for 
        // about a second. Each thread "works" a little 
        // longer, just to make the output more orderly.
        //
        Thread.Sleep(1000 + padding);

        Console.WriteLine("Thread {0} releases the semaphore.", num);
        Console.WriteLine("Thread {0} previous semaphore count: {1}",
            num, _pool.Release());
    }
}
Imports System.Threading

Public Class Example

    ' A semaphore that simulates a limited resource pool.
    '
    Private Shared _pool As Semaphore

    ' A padding interval to make the output more orderly.
    Private Shared _padding As Integer

    <MTAThread> _
    Public Shared Sub Main()
        ' Create a semaphore that can satisfy up to three
        ' concurrent requests. Use an initial count of zero,
        ' so that the entire semaphore count is initially
        ' owned by the main program thread.
        '
        _pool = New Semaphore(0, 3)

        ' Create and start five numbered threads. 
        '
        For i As Integer = 1 To 5
            Dim t As New Thread(New ParameterizedThreadStart(AddressOf Worker))
            'Dim t As New Thread(AddressOf Worker)

            ' Start the thread, passing the number.
            '
            t.Start(i)
        Next i

        ' Wait for half a second, to allow all the
        ' threads to start and to block on the semaphore.
        '
        Thread.Sleep(500)

        ' The main thread starts out holding the entire
        ' semaphore count. Calling Release(3) brings the 
        ' semaphore count back to its maximum value, and
        ' allows the waiting threads to enter the semaphore,
        ' up to three at a time.
        '
        Console.WriteLine("Main thread calls Release(3).")
        _pool.Release(3)

        Console.WriteLine("Main thread exits.")
    End Sub

    Private Shared Sub Worker(ByVal num As Object)
        ' Each worker thread begins by requesting the
        ' semaphore.
        Console.WriteLine("Thread {0} begins " _
            & "and waits for the semaphore.", num)
        _pool.WaitOne()

        ' A padding interval to make the output more orderly.
        Dim padding As Integer = Interlocked.Add(_padding, 100)

        Console.WriteLine("Thread {0} enters the semaphore.", num)
        
        ' The thread's "work" consists of sleeping for 
        ' about a second. Each thread "works" a little 
        ' longer, just to make the output more orderly.
        '
        Thread.Sleep(1000 + padding)

        Console.WriteLine("Thread {0} releases the semaphore.", num)
        Console.WriteLine("Thread {0} previous semaphore count: {1}", _
            num, _
            _pool.Release())
    End Sub
End Class

注釈

このコンストラクターは、名前のないセマフォを初期化します。 このようなセマフォのインスタンスを使用するすべてのスレッドには、 インスタンスへの参照が必要です。

が よりmaximumCount小さい場合initialCount、効果は、現在のスレッドが (maximumCount マイナス initialCount) 回を呼び出WaitOneした場合と同じです。 セマフォを作成するスレッドのエントリを予約しない場合は、 と initialCountに同じ番号をmaximumCount使用します。

こちらもご覧ください

適用対象

Semaphore(Int32, Int32, String)

エントリ数の初期値と同時実行エントリの最大数を指定し、オプションでシステム セマフォ オブジェクトの名前を指定して、Semaphore クラスの新しいインスタンスを初期化します。

public:
 Semaphore(int initialCount, int maximumCount, System::String ^ name);
public Semaphore (int initialCount, int maximumCount, string name);
public Semaphore (int initialCount, int maximumCount, string? name);
new System.Threading.Semaphore : int * int * string -> System.Threading.Semaphore
Public Sub New (initialCount As Integer, maximumCount As Integer, name As String)

パラメーター

initialCount
Int32

同時に許可されるセマフォの要求の初期数。

maximumCount
Int32

同時に許可されるセマフォの要求の最大数。

name
String

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

例外

initialCountmaximumCount より大きくなっています。

または

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

maximumCount が 1 未満です。

または

initialCount が 0 未満です。

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

または

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

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

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

アクセス制御セキュリティを使用した名前付きセマフォが存在しており、ユーザーに FullControl がありません。

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

次のコード例は、名前付きセマフォのクロスプロセス動作を示しています。 この例では、最大カウントが 5、初期カウントが 5 の名前付きセマフォを作成します。 プログラムは、 メソッドを WaitOne 3 回呼び出します。 したがって、2 つのコマンド ウィンドウからコンパイルされた例を実行すると、2 番目のコピーは への WaitOne3 回目の呼び出しでブロックされます。 プログラムの最初のコピーで 1 つ以上のエントリを解放して、2 番目のエントリのブロックを解除します。

#using <System.dll>
using namespace System;
using namespace System::Threading;

public ref class Example
{
public:
   static void main()
   {
      // Create a Semaphore object that represents the named
      // system semaphore "SemaphoreExample3". The semaphore has a
      // maximum count of five. The initial count is also five.
      // There is no point in using a smaller initial count,
      // because the initial count is not used if this program
      // doesn't create the named system semaphore, and with
      // this method overload there is no way to tell. Thus, this
      // program assumes that it is competing with other
      // programs for the semaphore.
      //
      Semaphore^ sem = gcnew Semaphore( 5,5,L"SemaphoreExample3" );
      
      // Attempt to enter the semaphore three times. If another
      // copy of this program is already running, only the first
      // two requests can be satisfied. The third blocks. Note
      // that in a real application, timeouts should be used
      // on the WaitOne calls, to avoid deadlocks.
      //
      sem->WaitOne();
      Console::WriteLine( L"Entered the semaphore once." );
      sem->WaitOne();
      Console::WriteLine( L"Entered the semaphore twice." );
      sem->WaitOne();
      Console::WriteLine( L"Entered the semaphore three times." );
      
      // The thread executing this program has entered the
      // semaphore three times. If a second copy of the program
      // is run, it will block until this program releases the
      // semaphore at least once.
      //
      Console::WriteLine( L"Enter the number of times to call Release." );
      int n;
      if ( Int32::TryParse( Console::ReadLine(),n ) )
      {
         sem->Release( n );
      }

      int remaining = 3 - n;
      if ( remaining > 0 )
      {
         Console::WriteLine( L"Press Enter to release the remaining "
         L"count ({0}) and exit the program.", remaining );
         Console::ReadLine();
         sem->Release( remaining );
      }
   }
};
using System;
using System.Threading;

public class Example
{
    public static void Main()
    {
        // Create a Semaphore object that represents the named 
        // system semaphore "SemaphoreExample3". The semaphore has a
        // maximum count of five. The initial count is also five. 
        // There is no point in using a smaller initial count,
        // because the initial count is not used if this program
        // doesn't create the named system semaphore, and with 
        // this method overload there is no way to tell. Thus, this
        // program assumes that it is competing with other
        // programs for the semaphore.
        //
        Semaphore sem = new Semaphore(5, 5, "SemaphoreExample3");

        // Attempt to enter the semaphore three times. If another 
        // copy of this program is already running, only the first
        // two requests can be satisfied. The third blocks. Note 
        // that in a real application, timeouts should be used
        // on the WaitOne calls, to avoid deadlocks.
        //
        sem.WaitOne();
        Console.WriteLine("Entered the semaphore once.");
        sem.WaitOne();
        Console.WriteLine("Entered the semaphore twice.");
        sem.WaitOne();
        Console.WriteLine("Entered the semaphore three times.");

        // The thread executing this program has entered the 
        // semaphore three times. If a second copy of the program
        // is run, it will block until this program releases the 
        // semaphore at least once.
        //
        Console.WriteLine("Enter the number of times to call Release.");
        int n;
        if (int.TryParse(Console.ReadLine(), out n))
        {
            sem.Release(n);
        }

        int remaining = 3 - n;
        if (remaining > 0)
        {
            Console.WriteLine("Press Enter to release the remaining " +
                "count ({0}) and exit the program.", remaining);
            Console.ReadLine();
            sem.Release(remaining);
        }
    }
}
Imports System.Threading

Public Class Example

    <MTAThread> _
    Public Shared Sub Main()
        ' Create a Semaphore object that represents the named 
        ' system semaphore "SemaphoreExample3". The semaphore has a
        ' maximum count of five. The initial count is also five. 
        ' There is no point in using a smaller initial count,
        ' because the initial count is not used if this program
        ' doesn't create the named system semaphore, and with 
        ' this method overload there is no way to tell. Thus, this
        ' program assumes that it is competing with other
        ' programs for the semaphore.
        '
        Dim sem As New Semaphore(5, 5, "SemaphoreExample3")

        ' Attempt to enter the semaphore three times. If another 
        ' copy of this program is already running, only the first
        ' two requests can be satisfied. The third blocks. Note 
        ' that in a real application, timeouts should be used
        ' on the WaitOne calls, to avoid deadlocks.
        '
        sem.WaitOne()
        Console.WriteLine("Entered the semaphore once.")
        sem.WaitOne()
        Console.WriteLine("Entered the semaphore twice.")
        sem.WaitOne()
        Console.WriteLine("Entered the semaphore three times.")

        ' The thread executing this program has entered the 
        ' semaphore three times. If a second copy of the program
        ' is run, it will block until this program releases the 
        ' semaphore at least once.
        '
        Console.WriteLine("Enter the number of times to call Release.")
        Dim n As Integer
        If Integer.TryParse(Console.ReadLine(), n) Then
            sem.Release(n)
        End If

        Dim remaining As Integer = 3 - n
        If (remaining) > 0 Then
            Console.WriteLine("Press Enter to release the remaining " _
                & "count ({0}) and exit the program.", remaining)
            Console.ReadLine()
            sem.Release(remaining)
        End If

    End Sub 
End Class

注釈

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

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

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

名前付きシステム セマフォが存在しない場合は、 と maximumCountで指定された初期カウントと最大カウントを使用してinitialCount作成されます。 名前付きシステム セマフォが既に存在しmaximumCountinitialCount使用されていない場合は、無効な値が引き続き例外を引き起こします。 名前付きシステム セマフォが作成されたかどうかを判断する必要がある場合は、代わりにコンストラクター オーバーロードを Semaphore(Int32, Int32, String, Boolean) 使用します。

重要

このコンストラクター オーバーロードを使用する場合は、 と maximumCountに同じ数initialCountを指定することをお勧めします。 が よりmaximumCount小さく、名前付きシステム セマフォが作成された場合initialCount、現在のスレッドが (maximumCount マイナス initialCount) 回を呼び出WaitOneした場合と同じ効果が得られます。 ただし、このコンストラクター オーバーロードでは、名前付きシステム セマフォが作成されたかどうかを判断する方法はありません。

または に空の文字列nameを指定nullすると、コンストラクター オーバーロードを呼び出した場合と同様に、ローカル セマフォがSemaphore(Int32, Int32)作成されます。

名前付きセマフォはオペレーティング システム全体で表示されるため、プロセス境界を越えてリソースの使用を調整するために使用できます。

名前付きシステム セマフォが存在するかどうかを調べるには、 メソッドを使用します OpenExisting 。 メソッドは OpenExisting 既存の名前付きセマフォを開こうとし、システム セマフォが存在しない場合は例外をスローします。

注意事項

既定では、名前付きセマフォは、それを作成したユーザーに制限されません。 セマフォを複数回取得して解放しないことでセマフォを妨害するなど、他のユーザーがセマフォを開いて使用できる場合があります。 特定のユーザーへのアクセスを制限するには、コンストラクターのオーバーロードを使用するか SemaphoreAcl 、名前付きセマフォを作成するときに を渡します SemaphoreSecurity 。 信頼されていないユーザーがコードを実行している可能性があるシステムでは、アクセス制限なしで名前付きセマフォを使用しないでください。

こちらもご覧ください

適用対象

Semaphore(Int32, Int32, String, Boolean)

エントリ数の初期値と同時実行エントリの最大数を指定し、オプションでシステム セマフォ オブジェクトの名前を指定し、新しいシステム セマフォが作成されたかどうかを示す値を受け取る変数を指定して、Semaphore クラスの新しいインスタンスを初期化します。

public:
 Semaphore(int initialCount, int maximumCount, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew);
public Semaphore (int initialCount, int maximumCount, string name, out bool createdNew);
public Semaphore (int initialCount, int maximumCount, string? name, out bool createdNew);
new System.Threading.Semaphore : int * int * string * bool -> System.Threading.Semaphore
Public Sub New (initialCount As Integer, maximumCount As Integer, name As String, ByRef createdNew As Boolean)

パラメーター

initialCount
Int32

同時に満たされるセマフォの要求の初期数。

maximumCount
Int32

同時に満たされるセマフォの要求の最大数。

name
String

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

createdNew
Boolean

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

例外

initialCountmaximumCount より大きくなっています。

または

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

maximumCount が 1 未満です。

または

initialCount が 0 未満です。

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

または

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

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

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

アクセス制御セキュリティを使用した名前付きセマフォが存在しており、ユーザーに FullControl がありません。

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

次のコード例は、名前付きセマフォのクロスプロセス動作を示しています。 この例では、最大カウントが 5 で、初期カウントが 2 の名前付きセマフォを作成します。 つまり、コンストラクターを呼び出すスレッドに対して 3 つのエントリを予約します。 が falseの場合createNew、プログラムは メソッドを WaitOne 3 回呼び出します。 したがって、2 つのコマンド ウィンドウからコンパイルされた例を実行すると、2 番目のコピーは への WaitOne3 回目の呼び出しでブロックされます。 プログラムの最初のコピーで 1 つ以上のエントリを解放して、2 番目のエントリのブロックを解除します。

#using <System.dll>
using namespace System;
using namespace System::Threading;

public ref class Example
{
public:
   static void main()
   {
      // 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 a Semaphore object that represents the named
      // system semaphore "SemaphoreExample". The semaphore has a
      // maximum count of five, and an initial count of two. The
      // Boolean value that indicates creation of the underlying
      // system object is placed in semaphoreWasCreated.
      //
      Semaphore^ sem = gcnew Semaphore( 2,5,L"SemaphoreExample",
         semaphoreWasCreated );
      if ( semaphoreWasCreated )
      {
         // If the named system semaphore was created, its count is
         // set to the initial count requested in the constructor.
         // In effect, the current thread has entered the semaphore
         // three times.
         //
         Console::WriteLine( L"Entered the semaphore three times." );
      }
      else
      {
         // If the named system semaphore was not created,
         // attempt to enter it three times. If another copy of
         // this program is already running, only the first two
         // requests can be satisfied. The third blocks.
         //
         sem->WaitOne();
         Console::WriteLine( L"Entered the semaphore once." );
         sem->WaitOne();
         Console::WriteLine( L"Entered the semaphore twice." );
         sem->WaitOne();
         Console::WriteLine( L"Entered the semaphore three times." );
      }
      
      // The thread executing this program has entered the
      // semaphore three times. If a second copy of the program
      // is run, it will block until this program releases the
      // semaphore at least once.
      //
      Console::WriteLine( L"Enter the number of times to call Release." );
      int n;
      if ( Int32::TryParse( Console::ReadLine(), n ) )
      {
         sem->Release( n );
      }

      int remaining = 3 - n;
      if ( remaining > 0 )
      {
         Console::WriteLine( L"Press Enter to release the remaining "
         L"count ({0}) and exit the program.", remaining );
         Console::ReadLine();
         sem->Release( remaining );
      }
   }
};
using System;
using System.Threading;

public class Example
{
    public static void Main()
    {
        // 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 a Semaphore object that represents the named 
        // system semaphore "SemaphoreExample". The semaphore has a
        // maximum count of five, and an initial count of two. The
        // Boolean value that indicates creation of the underlying 
        // system object is placed in semaphoreWasCreated.
        //
        Semaphore sem = new Semaphore(2, 5, "SemaphoreExample", 
            out semaphoreWasCreated);

        if (semaphoreWasCreated)
        {
            // If the named system semaphore was created, its count is
            // set to the initial count requested in the constructor.
            // In effect, the current thread has entered the semaphore
            // three times.
            // 
            Console.WriteLine("Entered the semaphore three times.");
        }
        else
        {      
            // If the named system semaphore was not created,  
            // attempt to enter it three times. If another copy of
            // this program is already running, only the first two
            // requests can be satisfied. The third blocks.
            //
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore once.");
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore twice.");
            sem.WaitOne();
            Console.WriteLine("Entered the semaphore three times.");
        }

        // The thread executing this program has entered the 
        // semaphore three times. If a second copy of the program
        // is run, it will block until this program releases the 
        // semaphore at least once.
        //
        Console.WriteLine("Enter the number of times to call Release.");
        int n;
        if (int.TryParse(Console.ReadLine(), out n))
        {
            sem.Release(n);
        }

        int remaining = 3 - n;
        if (remaining > 0)
        {
            Console.WriteLine("Press Enter to release the remaining " +
                "count ({0}) and exit the program.", remaining);
            Console.ReadLine();
            sem.Release(remaining);
        }
    } 
}
Imports System.Threading

Public Class Example

    <MTAThread> _
    Public Shared Sub Main()
        ' 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 a Semaphore object that represents the named 
        ' system semaphore "SemaphoreExample". The semaphore has a
        ' maximum count of five, and an initial count of two. The
        ' Boolean value that indicates creation of the underlying 
        ' system object is placed in semaphoreWasCreated.
        '
        Dim sem As New Semaphore(2, 5, "SemaphoreExample", _
            semaphoreWasCreated)

        If semaphoreWasCreated Then
            ' If the named system semaphore was created, its count is
            ' set to the initial count requested in the constructor.
            ' In effect, the current thread has entered the semaphore
            ' three times.
            ' 
            Console.WriteLine("Entered the semaphore three times.")
        Else
            ' If the named system semaphore was not created,  
            ' attempt to enter it three times. If another copy of
            ' this program is already running, only the first two
            ' requests can be satisfied. The third blocks.
            '
            sem.WaitOne()
            Console.WriteLine("Entered the semaphore once.")
            sem.WaitOne()
            Console.WriteLine("Entered the semaphore twice.")
            sem.WaitOne()
            Console.WriteLine("Entered the semaphore three times.")
        End If

        ' The thread executing this program has entered the 
        ' semaphore three times. If a second copy of the program
        ' is run, it will block until this program releases the 
        ' semaphore at least once.
        '
        Console.WriteLine("Enter the number of times to call Release.")
        Dim n As Integer
        If Integer.TryParse(Console.ReadLine(), n) Then
            sem.Release(n)
        End If

        Dim remaining As Integer = 3 - n
        If (remaining) > 0 Then
            Console.WriteLine("Press Enter to release the remaining " _
                & "count ({0}) and exit the program.", remaining)
            Console.ReadLine()
            sem.Release(remaining)
        End If

    End Sub 
End Class

注釈

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

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

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

名前付きシステム セマフォが存在しない場合は、 および maximumCountで指定された初期カウントと最大カウントを使用してinitialCount作成されます。 名前付きシステム セマフォが既に存在しmaximumCountinitialCount使用されていない場合は、無効な値が引き続き例外を引き起こします。 システム セマフォが作成されたかどうかを判断するには、 を使用 createdNew します。

が よりmaximumCount小さく、 createdNew が のtrue場合initialCount、効果は現在のスレッドが (maximumCount - initialCount) 回を呼び出WaitOneした場合と同じです。

または に空の文字列nameを指定nullすると、コンストラクター オーバーロードを呼び出したかのようにローカル セマフォがSemaphore(Int32, Int32)作成されます。 この場合、 createdNew は常に trueです。

名前付きセマフォはオペレーティング システム全体で表示されるため、プロセス境界を越えてリソースの使用を調整するために使用できます。

注意事項

既定では、名前付きセマフォは、そのセマフォを作成したユーザーに限定されません。 セマフォを複数回取得して解放しないことでセマフォを妨害するなど、他のユーザーがセマフォを開いて使用できる場合があります。 特定のユーザーへのアクセスを制限するには、名前付きセマフォを作成するときにコンストラクター オーバーロードを使用するか SemaphoreAcl 、 を渡します SemaphoreSecurity 。 信頼されていないユーザーがコードを実行している可能性があるシステムでは、アクセス制限なしで名前付きセマフォを使用しないでください。

こちらもご覧ください

適用対象

Semaphore(Int32, Int32, String, Boolean, SemaphoreSecurity)

エントリ数の初期値と同時実行エントリの最大数を指定し、オプションでシステム セマフォ オブジェクトの名前を指定し、新しいシステム セマフォが作成されたかどうかを示す値を受け取る変数を指定し、システム セマフォのセキュリティ アクセス制御を指定して、Semaphore クラスの新しいインスタンスを初期化します。

public:
 Semaphore(int initialCount, int maximumCount, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew, System::Security::AccessControl::SemaphoreSecurity ^ semaphoreSecurity);
public Semaphore (int initialCount, int maximumCount, string name, out bool createdNew, System.Security.AccessControl.SemaphoreSecurity semaphoreSecurity);
new System.Threading.Semaphore : int * int * string * bool * System.Security.AccessControl.SemaphoreSecurity -> System.Threading.Semaphore
Public Sub New (initialCount As Integer, maximumCount As Integer, name As String, ByRef createdNew As Boolean, semaphoreSecurity As SemaphoreSecurity)

パラメーター

initialCount
Int32

同時に満たされるセマフォの要求の初期数。

maximumCount
Int32

同時に満たされるセマフォの要求の最大数。

name
String

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

createdNew
Boolean

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

semaphoreSecurity
SemaphoreSecurity

名前付きシステム セマフォに適用するアクセス制御セキュリティを表す SemaphoreSecurity オブジェクト。

例外

initialCountmaximumCount より大きくなっています。

または

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

maximumCount が 1 未満です。

または

initialCount が 0 未満です。

アクセス制御セキュリティを使用した名前付きセマフォが存在しており、ユーザーに FullControl がありません。

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

または

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

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

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

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

次のコード例は、アクセス制御セキュリティを使用した名前付きセマフォのクロスプロセス動作を示しています。 この例では、 メソッド オーバーロードを OpenExisting(String) 使用して、名前付きセマフォの存在をテストします。 セマフォが存在しない場合、セマフォは最大カウント 2 で作成され、アクセス制御セキュリティにより、現在のユーザーはセマフォを使用する権限を拒否しますが、セマフォに対する読み取りと変更のアクセス許可を付与します。 2 つのコマンド ウィンドウからコンパイルされた例を実行すると、2 番目のコピーは メソッドの呼び出しでアクセス違反例外を OpenExisting(String) スローします。 例外がキャッチされ、この例では メソッド オーバーロードを OpenExisting(String, SemaphoreRights) 使用して、アクセス許可の読み取りと変更に必要な権限を持つセマフォを開きます。

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

#using <System.dll>
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^ semaphoreName = L"SemaphoreExample5";

      Semaphore^ sem = nullptr;
      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^ ex ) 
      {
         Console::WriteLine( L"Semaphore does not exist." );
         doesNotExist = true;
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"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 = String::Concat( Environment::UserDomainName,
            L"\\", Environment::UserName );
         SemaphoreSecurity^ semSec = gcnew SemaphoreSecurity;

         SemaphoreAccessRule^ rule = gcnew SemaphoreAccessRule( user,
            static_cast<SemaphoreRights>(
               SemaphoreRights::Synchronize |
               SemaphoreRights::Modify ),
            AccessControlType::Deny );
         semSec->AddAccessRule( rule );

         rule = gcnew SemaphoreAccessRule( user,
            static_cast<SemaphoreRights>(
               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 = gcnew 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 )
         {
            Console::WriteLine( L"Created the semaphore." );
         }
         else
         {
            Console::WriteLine( L"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,
               static_cast<SemaphoreRights>(
                  SemaphoreRights::ReadPermissions |
                  SemaphoreRights::ChangePermissions ));
            
            // Get the current ACL. This requires
            // SemaphoreRights.ReadPermissions.
            SemaphoreSecurity^ semSec = sem->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 semaphore must
            // be removed.
            SemaphoreAccessRule^ rule = gcnew SemaphoreAccessRule( user,
               static_cast<SemaphoreRights>(
                  SemaphoreRights::Synchronize |
                  SemaphoreRights::Modify ),
               AccessControlType::Deny );
            semSec->RemoveAccessRule( rule );
            
            // Now grant the user the correct rights.
            //
            rule = gcnew SemaphoreAccessRule( user,
               static_cast<SemaphoreRights>(
                  SemaphoreRights::Synchronize |
                  SemaphoreRights::Modify ),
               AccessControlType::Allow );
            semSec->AddAccessRule( rule );
            
            // Update the ACL. This requires
            // SemaphoreRights.ChangePermissions.
            sem->SetAccessControl( semSec );

            Console::WriteLine( L"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( L"Unable to change permissions: {0}", ex->Message );
            return;
         }
      }
      
      // Enter the semaphore, and hold it until the program
      // exits.
      //
      try
      {
         sem->WaitOne();
         Console::WriteLine( L"Entered the semaphore." );
         Console::WriteLine( L"Press the Enter key to exit." );
         Console::ReadLine();
         sem->Release();
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message );
      }
   }
};
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 での同期オブジェクト名の詳細については、「 オブジェクト名」を参照してください。

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

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

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

Note

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

名前付きシステム セマフォが存在しない場合は、 と maximumCountで指定された初期カウントと最大カウントを使用してinitialCount作成されます。 名前付きシステム セマフォが既に存在しmaximumCountinitialCount使用されていない場合は、無効な値が引き続き例外を引き起こします。 createdNewこのコンストラクターによってシステム セマフォが作成されたかどうかを判断するには、 パラメーターを使用します。

が よりmaximumCount小さく、 createdNew が のtrue場合initialCount、効果は、現在のスレッドが (maximumCount マイナス initialCount) 回を呼び出WaitOneした場合と同じです。

または に空の文字列nameを指定nullすると、コンストラクター オーバーロードを呼び出した場合と同様に、ローカル セマフォがSemaphore(Int32, Int32)作成されます。 この場合、 createdNew は常に trueです。

名前付きセマフォはオペレーティング システム全体で表示されるため、プロセス境界を越えてリソースの使用を調整するために使用できます。

注意事項

既定では、名前付きセマフォは、それを作成したユーザーに制限されません。 セマフォを複数回取得して解放しないことでセマフォを妨害するなど、他のユーザーがセマフォを開いて使用できる場合があります。 特定のユーザーへのアクセスを制限するために、名前付きセマフォを作成するときに を渡 SemaphoreSecurity すことができます。 信頼されていないユーザーがコードを実行している可能性があるシステムでは、アクセス制限なしで名前付きセマフォを使用しないでください。

こちらもご覧ください

適用対象