Semaphore Semaphore Semaphore Semaphore Constructors

定義

オーバーロード

Semaphore(Int32, Int32) Semaphore(Int32, Int32) Semaphore(Int32, Int32) Semaphore(Int32, Int32)

エントリ数の初期値と同時実行エントリの最大数を指定して、Semaphore クラスの新しいインスタンスを初期化します。Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries.

Semaphore(Int32, Int32, String) Semaphore(Int32, Int32, String) Semaphore(Int32, Int32, String) Semaphore(Int32, Int32, String)

エントリ数の初期値と同時実行エントリの最大数を指定し、オプションでシステム セマフォ オブジェクトの名前を指定して、Semaphore クラスの新しいインスタンスを初期化します。Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, and optionally specifying the name of a system semaphore object.

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

エントリ数の初期値と同時実行エントリの最大数を指定し、オプションでシステム セマフォ オブジェクトの名前を指定し、新しいシステム セマフォが作成されたかどうかを示す値を受け取る変数を指定して、Semaphore クラスの新しいインスタンスを初期化します。Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, optionally specifying the name of a system semaphore object, and specifying a variable that receives a value indicating whether a new system semaphore was created.

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

エントリ数の初期値と同時実行エントリの最大数を指定し、オプションでシステム セマフォ オブジェクトの名前を指定し、新しいシステム セマフォが作成されたかどうかを示す値を受け取る変数を指定し、システム セマフォのセキュリティ アクセス制御を指定して、Semaphore クラスの新しいインスタンスを初期化します。Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, optionally specifying the name of a system semaphore object, specifying a variable that receives a value indicating whether a new system semaphore was created, and specifying security access control for the system semaphore.

Semaphore(Int32, Int32) Semaphore(Int32, Int32) Semaphore(Int32, Int32) Semaphore(Int32, Int32)

エントリ数の初期値と同時実行エントリの最大数を指定して、Semaphore クラスの新しいインスタンスを初期化します。Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries.

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 Int32 Int32 Int32

同時に許可されるセマフォの要求の初期数。The initial number of requests for the semaphore that can be granted concurrently.

maximumCount
Int32 Int32 Int32 Int32

同時に許可されるセマフォの要求の最大数。The maximum number of requests for the semaphore that can be granted concurrently.

例外

initialCountmaximumCount より大きくなっています。initialCount is greater than maximumCount.

maximumCount が 1 未満です。maximumCount is less than 1.

または-or- initialCount が 0 未満です。initialCount is less than 0.

次の例では、最大数が3で、初期カウントが0のセマフォを作成します。The following example creates a semaphore with a maximum count of three and an initial count of zero. この例では、5つのスレッドを開始します。これは、セマフォを待機しています。The example starts five threads, which block waiting for the semaphore. メインスレッドは、 Release(Int32)メソッドオーバーロードを使用してセマフォ数を最大値に増やし、3つのスレッドがセマフォに入ることができるようにします。The main thread uses the Release(Int32) method overload to increase the semaphore count to its maximum, allowing three threads to enter the semaphore. 各スレッドは、 Thread.Sleepメソッドを使用して1秒間待機し、作業をシミュレートしRelease()た後、メソッドオーバーロードを呼び出してセマフォを解放します。Each thread uses the Thread.Sleep method to wait for one second, to simulate work, and then calls the Release() method overload to release the semaphore. セマフォが解放されるたびに、前のセマフォ数が表示されます。Each time the semaphore is released, the previous semaphore count is displayed. コンソールメッセージは、セマフォの使用を追跡します。Console messages track semaphore use. シミュレートされた作業間隔は、出力を読みやすくするために、スレッドごとに若干増加します。The simulated work interval is increased slightly for each thread, to make the output easier to read.

#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(0, 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(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
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

注釈

このコンストラクターは、名前のないセマフォを初期化します。This constructor initializes an unnamed semaphore. このようなセマフォのインスタンスを使用するすべてのスレッドは、インスタンスへの参照を持っている必要があります。All threads that use an instance of such a semaphore must have references to the instance.

initialCountよりWaitOne maximumCount initialCount小さい場合、効果は、現在のスレッドが (負の値を引いた) 時間を呼び出した場合と同じです。 maximumCountIf initialCount is less than maximumCount, the effect is the same as if the current thread had called WaitOne (maximumCount minus initialCount) times. セマフォを作成するスレッドのエントリを予約しない場合は、とmaximumCount initialCountの同じ数値を使用します。If you do not want to reserve any entries for the thread that creates the semaphore, use the same number for maximumCount and initialCount.

こちらもご覧ください

Semaphore(Int32, Int32, String) Semaphore(Int32, Int32, String) Semaphore(Int32, Int32, String) Semaphore(Int32, Int32, String)

エントリ数の初期値と同時実行エントリの最大数を指定し、オプションでシステム セマフォ オブジェクトの名前を指定して、Semaphore クラスの新しいインスタンスを初期化します。Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, and optionally specifying the name of a system semaphore object.

public:
 Semaphore(int initialCount, int maximumCount, System::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 Int32 Int32 Int32

同時に許可されるセマフォの要求の初期数。The initial number of requests for the semaphore that can be granted concurrently.

maximumCount
Int32 Int32 Int32 Int32

同時に許可されるセマフォの要求の最大数。The maximum number of requests for the semaphore that can be granted concurrently.

name
String String String String

名前付きシステム セマフォ オブジェクトの名前。The name of a named system semaphore object.

例外

initialCountmaximumCount より大きくなっています。initialCount is greater than maximumCount.

- または --or- name が 260 文字を超えています。name is longer than 260 characters.

maximumCount が 1 未満です。maximumCount is less than 1.

- または --or- initialCount が 0 未満です。initialCount is less than 0.

Win32 エラーが発生しました。A Win32 error occurred.

アクセス制御セキュリティを使用した名前付きセマフォが存在しており、ユーザーに FullControl がありません。The named semaphore exists and has access control security, and the user does not have FullControl.

名前付きセマフォを作成できません。原因として、別の型の待機ハンドルに同じ名前が付けられていることが考えられます。The named semaphore cannot be created, perhaps because a wait handle of a different type has the same name.

名前付きセマフォのプロセス間の動作を示すコード例を次に示します。The following code example demonstrates the cross-process behavior of a named semaphore. この例では、最大数が5で、初期カウントが5である名前付きセマフォを作成します。The example creates a named semaphore with a maximum count of five and an initial count of five. このプログラムは、 WaitOneメソッドを3回呼び出します。The program makes three calls to the WaitOne method. したがって、コンパイルされた例を2つのコマンドウィンドウから実行した場合、2番目WaitOneのコピーはの3回目の呼び出しでブロックされます。Thus, if you run the compiled example from two command windows, the second copy will block on the third call to WaitOne. プログラムの最初のコピーの1つ以上のエントリを解放して、2番目のブロックのブロックを解除します。Release one or more entries in the first copy of the program to unblock the second.

#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
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名前付きシステムセマフォを表すオブジェクトを初期化します。This constructor initializes a Semaphore object that represents a named system semaphore. 同じ名前付きシステムSemaphoreセマフォを表す複数のオブジェクトを作成できます。You can create multiple Semaphore objects that represent the same named system semaphore.

名前付きシステムセマフォが存在しない場合は、とinitialCount maximumCountで指定された初期カウントと最大カウントを使用して作成されます。If the named system semaphore does not exist, it is created with the initial count and maximum count specified by initialCount and maximumCount. 名前付きシステムセマフォが既に存在initialCount maximumCountし、使用されていない場合でも、無効な値によって例外が発生します。If the named system semaphore already exists, initialCount and maximumCount are not used, although invalid values still cause exceptions. 名前付きシステムセマフォが作成されたかどうかを判断する必要がSemaphore(Int32, Int32, String, Boolean)ある場合は、代わりにコンストラクターのオーバーロードを使用します。If you need to determine whether or not a named system semaphore was created, use the Semaphore(Int32, Int32, String, Boolean) constructor overload instead.

重要

このコンストラクターのオーバーロードを使用する場合、とinitialCount maximumCountに同じ数値を指定することをお勧めします。When you use this constructor overload, the recommended practice is to specify the same number for initialCount and maximumCount. initialCountよりWaitOne maximumCount initialCount小さい場合、および名前付きシステムセマフォが作成されると、その効果は、現在のスレッドが (負の値から) を呼び出した場合と同じになります。 maximumCountIf initialCount is less than maximumCount, and a named system semaphore is created, the effect is the same as if the current thread had called WaitOne (maximumCount minus initialCount) times. ただし、このコンストラクターのオーバーロードでは、名前付きシステムセマフォが作成されたかどうかを判断する方法はありません。However, with this constructor overload there is no way to determine whether a named system semaphore was created.

またはにnull空のname文字列を指定すると、 Semaphore(Int32, Int32)コンストラクターのオーバーロードを呼び出した場合と同様に、ローカルセマフォが作成されます。If you specify null or an empty string for name, a local semaphore is created, as if you had called the Semaphore(Int32, Int32) constructor overload.

名前付きセマフォはオペレーティングシステム全体にわたって表示されるため、プロセスの境界を越えてリソースの使用量を調整するために使用できます。Because named semaphores are visible throughout the operating system, they can be used to coordinate resource use across process boundaries.

名前付きシステムセマフォが存在するかどうかを確認するにはOpenExisting 、メソッドを使用します。If you want to find out whether a named system semaphore exists, use the OpenExisting method. メソッドOpenExistingは、既存の名前付きセマフォを開こうとし、システムセマフォが存在しない場合は例外をスローします。The OpenExisting method attempts to open an existing named semaphore, and throws an exception if the system semaphore does not exist.

セキュリティ

SecurityPermission
アンマネージコードを呼び出して名前付きシステムセマフォを作成する場合。for calling unmanaged code to create a named system semaphore. UnmanagedCode (関連する列挙体)Associated enumeration: UnmanagedCode. セキュリティアクション: LinkDemandSecurity action: LinkDemand.

こちらもご覧ください

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

エントリ数の初期値と同時実行エントリの最大数を指定し、オプションでシステム セマフォ オブジェクトの名前を指定し、新しいシステム セマフォが作成されたかどうかを示す値を受け取る変数を指定して、Semaphore クラスの新しいインスタンスを初期化します。Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, optionally specifying the name of a system semaphore object, and specifying a variable that receives a value indicating whether a new system semaphore was created.

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);
new System.Threading.Semaphore : int * int * string *  -> System.Threading.Semaphore
Public Sub New (initialCount As Integer, maximumCount As Integer, name As String, ByRef createdNew As Boolean)

パラメーター

initialCount
Int32 Int32 Int32 Int32

同時に満たされるセマフォの要求の初期数。The initial number of requests for the semaphore that can be satisfied concurrently.

maximumCount
Int32 Int32 Int32 Int32

同時に満たされるセマフォの要求の最大数。The maximum number of requests for the semaphore that can be satisfied concurrently.

name
String String String String

名前付きシステム セマフォ オブジェクトの名前。The name of a named system semaphore object.

createdNew
Boolean Boolean Boolean Boolean

このメソッドから制御が戻るときに、ローカル セマフォが作成された場合 (namenull または空の文字列の場合)、または指定した名前付きシステム セマフォが作成された場合は true が格納されます。指定した名前付きシステム セマフォが既に存在する場合は false が格納されます。When this method returns, contains true if a local semaphore was created (that is, if name is null or an empty string) or if the specified named system semaphore was created; false if the specified named system semaphore already existed. このパラメーターは初期化せずに渡されます。This parameter is passed uninitialized.

例外

initialCountmaximumCount より大きくなっています。initialCount is greater than maximumCount.

- または --or- name が 260 文字を超えています。name is longer than 260 characters.

maximumCount が 1 未満です。maximumCount is less than 1.

- または --or- initialCount が 0 未満です。initialCount is less than 0.

Win32 エラーが発生しました。A Win32 error occurred.

アクセス制御セキュリティを使用した名前付きセマフォが存在しており、ユーザーに FullControl がありません。The named semaphore exists and has access control security, and the user does not have FullControl.

名前付きセマフォを作成できません。原因として、別の型の待機ハンドルに同じ名前が付けられていることが考えられます。The named semaphore cannot be created, perhaps because a wait handle of a different type has the same name.

名前付きセマフォのプロセス間の動作を示すコード例を次に示します。The following code example demonstrates the cross-process behavior of a named semaphore. この例では、最大数が5で、初期カウントが2である名前付きセマフォを作成します。The example creates a named semaphore with a maximum count of five and an initial count of two. つまり、コンストラクターを呼び出すスレッドに対して、3つのエントリが予約されます。That is, it reserves three entries for the thread that calls the constructor. WaitOnecreateNewfalse場合、プログラムはメソッドを3回呼び出します。If createNew is false, the program makes three calls to the WaitOne method. したがって、コンパイルされた例を2つのコマンドウィンドウから実行した場合、2番目WaitOneのコピーはの3回目の呼び出しでブロックされます。Thus, if you run the compiled example from two command windows, the second copy will block on the third call to WaitOne. プログラムの最初のコピーの1つ以上のエントリを解放して、2番目のブロックのブロックを解除します。Release one or more entries in the first copy of the program to unblock the second.

#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
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 

注釈

このコンストラクターは、 Semaphore名前付きシステムセマフォを表すオブジェクトを初期化します。This constructor initializes a Semaphore object that represents a named system semaphore. 同じ名前付きシステムSemaphoreセマフォを表す複数のオブジェクトを作成できます。You can create multiple Semaphore objects that represent the same named system semaphore.

名前付きシステムセマフォが存在しない場合は、とinitialCount maximumCountで指定された初期カウントと最大カウントを使用して作成されます。If the named system semaphore does not exist, it is created with the initial count and maximum count specified by initialCount and maximumCount. 名前付きシステムセマフォが既に存在initialCount maximumCountし、使用されていない場合でも、無効な値によって例外が発生します。If the named system semaphore already exists, initialCount and maximumCount are not used, although invalid values still cause exceptions. システムcreatedNewセマフォが作成されたかどうかを判断するには、を使用します。Use createdNew to determine whether the system semaphore was created.

initialCountよりcreatedNew maximumCount WaitOne小さい場合、 initialCounttrueである場合、効果は、現在のスレッドが (負の) 時間を呼び出した場合と同じになります。 maximumCountIf initialCount is less than maximumCount, and createdNew is true, the effect is the same as if the current thread had called WaitOne (maximumCount minus initialCount) times.

またはにnull空のname文字列を指定すると、 Semaphore(Int32, Int32)コンストラクターのオーバーロードを呼び出した場合と同様に、ローカルセマフォが作成されます。If you specify null or an empty string for name, a local semaphore is created, as if you had called the Semaphore(Int32, Int32) constructor overload. この場合、 createdNewは常にtrueです。In this case, createdNew is always true.

名前付きセマフォはオペレーティングシステム全体にわたって表示されるため、プロセスの境界を越えてリソースの使用量を調整するために使用できます。Because named semaphores are visible throughout the operating system, they can be used to coordinate resource use across process boundaries.

セキュリティ

SecurityPermission
アンマネージコードを呼び出して名前付きシステムセマフォを作成する場合。for calling unmanaged code to create a named system semaphore. UnmanagedCode (関連する列挙体)Associated enumeration: UnmanagedCode. セキュリティアクション: LinkDemandSecurity action: LinkDemand.

こちらもご覧ください

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

エントリ数の初期値と同時実行エントリの最大数を指定し、オプションでシステム セマフォ オブジェクトの名前を指定し、新しいシステム セマフォが作成されたかどうかを示す値を受け取る変数を指定し、システム セマフォのセキュリティ アクセス制御を指定して、Semaphore クラスの新しいインスタンスを初期化します。Initializes a new instance of the Semaphore class, specifying the initial number of entries and the maximum number of concurrent entries, optionally specifying the name of a system semaphore object, specifying a variable that receives a value indicating whether a new system semaphore was created, and specifying security access control for the system 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 *  * System.Security.AccessControl.SemaphoreSecurity -> System.Threading.Semaphore

パラメーター

initialCount
Int32 Int32 Int32 Int32

同時に満たされるセマフォの要求の初期数。The initial number of requests for the semaphore that can be satisfied concurrently.

maximumCount
Int32 Int32 Int32 Int32

同時に満たされるセマフォの要求の最大数。The maximum number of requests for the semaphore that can be satisfied concurrently.

name
String String String String

名前付きシステム セマフォ オブジェクトの名前。The name of a named system semaphore object.

createdNew
Boolean Boolean Boolean Boolean

このメソッドから制御が戻るときに、ローカル セマフォが作成された場合 (namenull または空の文字列の場合)、または指定した名前付きシステム セマフォが作成された場合は true が格納されます。指定した名前付きシステム セマフォが既に存在する場合は false が格納されます。When this method returns, contains true if a local semaphore was created (that is, if name is null or an empty string) or if the specified named system semaphore was created; false if the specified named system semaphore already existed. このパラメーターは初期化せずに渡されます。This parameter is passed uninitialized.

semaphoreSecurity
SemaphoreSecurity SemaphoreSecurity SemaphoreSecurity SemaphoreSecurity

名前付きシステム セマフォに適用するアクセス制御セキュリティを表す SemaphoreSecurity オブジェクト。A SemaphoreSecurity object that represents the access control security to be applied to the named system semaphore.

例外

initialCountmaximumCount より大きくなっています。initialCount is greater than maximumCount.

- または --or- name が 260 文字を超えています。name is longer than 260 characters.

maximumCount が 1 未満です。maximumCount is less than 1.

- または --or- initialCount が 0 未満です。initialCount is less than 0.

アクセス制御セキュリティを使用した名前付きセマフォが存在しており、ユーザーに FullControl がありません。The named semaphore exists and has access control security, and the user does not have FullControl.

Win32 エラーが発生しました。A Win32 error occurred.

名前付きセマフォを作成できません。原因として、別の型の待機ハンドルに同じ名前が付けられていることが考えられます。The named semaphore cannot be created, perhaps because a wait handle of a different type has the same name.

次のコード例では、アクセス制御セキュリティを使用した名前付きセマフォのプロセス間の動作を示します。The following code example demonstrates the cross-process behavior of a named semaphore with access control security. この例ではOpenExisting(String) 、メソッドオーバーロードを使用して、名前付きセマフォが存在するかどうかをテストします。The example uses the OpenExisting(String) method overload to test for the existence of a named semaphore. セマフォが存在しない場合は、最大カウント2とアクセス制御セキュリティを使用して作成され、現在のユーザーがセマフォを使用する権限を拒否しますが、セマフォに対するアクセス許可の読み取りと変更の権限を付与します。If the semaphore does not exist, it is created with a maximum count of two and with access control security that denies the current user the right to use the semaphore but grants the right to read and change permissions on the semaphore. コンパイルされた例を2つのコマンドウィンドウから実行した場合、2番目のコピーでは、 OpenExisting(String)メソッドの呼び出しでアクセス違反例外がスローされます。If you run the compiled example from two command windows, the second copy will throw an access violation exception on the call to the OpenExisting(String) method. 例外がキャッチされ、この例ではOpenExisting(String, SemaphoreRights)メソッドオーバーロードを使用して、アクセス許可の読み取りと変更に必要な権限を持つセマフォを開きます。The exception is caught, and the example uses the OpenExisting(String, SemaphoreRights) method overload to open the semaphore with the rights needed to read and change the permissions.

アクセス許可が変更されると、セマフォを入力して解放するために必要な権限を使用してセマフォが開かれます。After the permissions are changed, the semaphore is opened with the rights required to enter and release. コンパイルされた例を3番目のコマンドウィンドウから実行すると、新しいアクセス許可を使用して実行されます。If you run the compiled example from a third command window, it runs using the new permissions.

#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
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 

注釈

このコンストラクターを使用して、名前付きシステムセマフォの作成時にアクセス制御セキュリティを適用し、他のコードがセマフォを制御できないようにします。Use this constructor to apply access control security to a named system semaphore when it is created, preventing other code from taking control of the semaphore.

このコンストラクターは、 Semaphore名前付きシステムセマフォを表すオブジェクトを初期化します。This constructor initializes a Semaphore object that represents a named system semaphore. 同じ名前付きシステムSemaphoreセマフォを表す複数のオブジェクトを作成できます。You can create multiple Semaphore objects that represent the same named system semaphore.

名前付きシステムセマフォが存在しない場合は、指定されたアクセス制御セキュリティを使用して作成されます。If the named system semaphore does not exist, it is created with the specified access control security. 名前付きセマフォが存在する場合、指定されたアクセス制御セキュリティは無視されます。If the named semaphore exists, the specified access control security is ignored.

注意

が現在のユーザーに対して一部のSemaphoreアクセス権をsemaphoreSecurity拒否または許可しない場合でも、呼び出し元は、新しく作成されたオブジェクトを完全に制御できます。The caller has full control over the newly created Semaphore object even if semaphoreSecurity denies or fails to grant some access rights to the current user. ただし、コンストラクター OpenExistingまたはメソッドを使用してSemaphore 、現在のユーザーが同じ名前のセマフォを表す別のオブジェクトを取得しようとすると、Windows アクセス制御セキュリティが適用されます。However, if the current user attempts to get another Semaphore object to represent the same named semaphore, using either a constructor or the OpenExisting method, Windows access control security is applied.

名前付きシステムセマフォが存在しない場合は、とinitialCount maximumCountで指定された初期カウントと最大カウントを使用して作成されます。If the named system semaphore does not exist, it is created with the initial count and maximum count specified by initialCount and maximumCount. 名前付きシステムセマフォが既に存在initialCount maximumCountし、使用されていない場合でも、無効な値によって例外が発生します。If the named system semaphore already exists, initialCount and maximumCount are not used, although invalid values still cause exceptions. createdNewパラメーターを使用して、システムセマフォがこのコンストラクターによって作成されたかどうかを確認します。Use the createdNew parameter to determine whether the system semaphore was created by this constructor.

initialCountよりcreatedNew maximumCount WaitOne小さい場合、 initialCounttrueである場合、効果は、現在のスレッドが (負の) 時間を呼び出した場合と同じになります。 maximumCountIf initialCount is less than maximumCount, and createdNew is true, the effect is the same as if the current thread had called WaitOne (maximumCount minus initialCount) times.

またはにnull空のname文字列を指定すると、 Semaphore(Int32, Int32)コンストラクターのオーバーロードを呼び出した場合と同様に、ローカルセマフォが作成されます。If you specify null or an empty string for name, a local semaphore is created, as if you had called the Semaphore(Int32, Int32) constructor overload. この場合、 createdNewは常にtrueです。In this case, createdNew is always true.

名前付きセマフォはオペレーティングシステム全体にわたって表示されるため、プロセスの境界を越えてリソースの使用量を調整するために使用できます。Because named semaphores are visible throughout the operating system, they can be used to coordinate resource use across process boundaries.

セキュリティ

SecurityPermission
アンマネージコードを呼び出して名前付きシステムセマフォを作成する場合。for calling unmanaged code to create a named system semaphore. UnmanagedCode (関連する列挙体)Associated enumeration: UnmanagedCode. セキュリティアクション: LinkDemandSecurity action: LinkDemand.

こちらもご覧ください

適用対象