EventWaitHandle コンストラクター

定義

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

オーバーロード

EventWaitHandle(Boolean, EventResetMode)

待機ハンドルの初期状態をシグナル状態に設定するかどうか、および、待機ハンドルが自動的にリセットされるかまたは手動でリセットされるかを指定して、EventWaitHandle クラスの新しいインスタンスを初期化します。

EventWaitHandle(Boolean, EventResetMode, String)

この呼び出しの結果として待機ハンドルが作成された場合に待機ハンドルの初期状態をシグナル状態に設定するかどうか、待機ハンドルが自動的にリセットされるかまたは手動でリセットされるか、およびシステムの同期イベントの名前を指定して、EventWaitHandle クラスの新しいインスタンスを初期化します。

EventWaitHandle(Boolean, EventResetMode, String, Boolean)

EventWaitHandle クラスの新しいインスタンスを初期化し、待機ハンドルがこの呼び出しの結果として作成された場合に最初にシグナル状態になるかどうか、リセットは自動または手動か、システムの同期イベントの名前、呼び出しの後の値で名前の付いたシステム イベントが作成されたかどうかを示すブール値変数を指定します。

EventWaitHandle(Boolean, EventResetMode, String, Boolean, EventWaitHandleSecurity)

EventWaitHandle クラスの新しいインスタンスを初期化し、待機ハンドルがこの呼び出しの結果として作成された場合に最初にシグナル状態になるかどうか、リセットは自動または手動か、システムの同期イベントの名前、呼び出しの後の値で名前の付いたシステム イベントが作成されたかどうかを示すブール値変数、および名前の付いたシステム イベントが作成された場合は、そのイベントにアクセス制御セキュリティを適用するかどうかを指定します。

EventWaitHandle(Boolean, EventResetMode)

ソース:
EventWaitHandle.cs
ソース:
EventWaitHandle.cs
ソース:
EventWaitHandle.cs

待機ハンドルの初期状態をシグナル状態に設定するかどうか、および、待機ハンドルが自動的にリセットされるかまたは手動でリセットされるかを指定して、EventWaitHandle クラスの新しいインスタンスを初期化します。

public:
 EventWaitHandle(bool initialState, System::Threading::EventResetMode mode);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode);
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode -> System.Threading.EventWaitHandle
Public Sub New (initialState As Boolean, mode As EventResetMode)

パラメーター

initialState
Boolean

初期状態をシグナル状態に設定する場合は true。非シグナル状態に設定する場合は false

mode
EventResetMode

イベントが自動的にリセットされるかまたは手動でリセットされるかを指定する EventResetMode 値の 1 つ。

例外

mode 列挙値が適正範囲外でした。

次のコード例では、 メソッド オーバーロードをSignalAndWait(WaitHandle, WaitHandle)使用して、メイン スレッドがブロックされたスレッドを通知し、スレッドがタスクを完了するまで待機できるようにします。

この例では、5 つのスレッドを開始し、 フラグを使用EventResetMode.AutoResetして作成された をEventWaitHandleブロックし、ユーザーが Enter キーを押すたびに 1 つのスレッドを解放できるようにします。 次に、この例では、別の 5 つのスレッドをキューに入れ、 フラグでEventResetMode.ManualReset作成された をEventWaitHandle使用して、それらすべてを解放します。

using namespace System;
using namespace System::Threading;

public ref class Example
{
private:
   // The EventWaitHandle used to demonstrate the difference
   // between AutoReset and ManualReset synchronization events.
   //
   static EventWaitHandle^ ewh;

   // A counter to make sure all threads are started and
   // blocked before any are released. A Long is used to show
   // the use of the 64-bit Interlocked methods.
   //
   static __int64 threadCount = 0;

   // An AutoReset event that allows the main thread to block
   // until an exiting thread has decremented the count.
   //
   static EventWaitHandle^ clearCount =
      gcnew EventWaitHandle( false,EventResetMode::AutoReset );

public:
   [MTAThread]
   static void main()
   {
      // Create an AutoReset EventWaitHandle.
      //
      ewh = gcnew EventWaitHandle( false,EventResetMode::AutoReset );
      
      // Create and start five numbered threads. Use the
      // ParameterizedThreadStart delegate, so the thread
      // number can be passed as an argument to the Start
      // method.
      for ( int i = 0; i <= 4; i++ )
      {
         Thread^ t = gcnew Thread(
            gcnew ParameterizedThreadStart( ThreadProc ) );
         t->Start( i );
      }
      
      // Wait until all the threads have started and blocked.
      // When multiple threads use a 64-bit value on a 32-bit
      // system, you must access the value through the
      // Interlocked class to guarantee thread safety.
      //
      while ( Interlocked::Read( threadCount ) < 5 )
      {
         Thread::Sleep( 500 );
      }

      // Release one thread each time the user presses ENTER,
      // until all threads have been released.
      //
      while ( Interlocked::Read( threadCount ) > 0 )
      {
         Console::WriteLine( L"Press ENTER to release a waiting thread." );
         Console::ReadLine();
         
         // SignalAndWait signals the EventWaitHandle, which
         // releases exactly one thread before resetting,
         // because it was created with AutoReset mode.
         // SignalAndWait then blocks on clearCount, to
         // allow the signaled thread to decrement the count
         // before looping again.
         //
         WaitHandle::SignalAndWait( ewh, clearCount );
      }
      Console::WriteLine();
      
      // Create a ManualReset EventWaitHandle.
      //
      ewh = gcnew EventWaitHandle( false,EventResetMode::ManualReset );
      
      // Create and start five more numbered threads.
      //
      for ( int i = 0; i <= 4; i++ )
      {
         Thread^ t = gcnew Thread(
            gcnew ParameterizedThreadStart( ThreadProc ) );
         t->Start( i );
      }
      
      // Wait until all the threads have started and blocked.
      //
      while ( Interlocked::Read( threadCount ) < 5 )
      {
         Thread::Sleep( 500 );
      }

      // Because the EventWaitHandle was created with
      // ManualReset mode, signaling it releases all the
      // waiting threads.
      //
      Console::WriteLine( L"Press ENTER to release the waiting threads." );
      Console::ReadLine();
      ewh->Set();

   }

   static void ThreadProc( Object^ data )
   {
      int index = static_cast<Int32>(data);

      Console::WriteLine( L"Thread {0} blocks.", data );
      // Increment the count of blocked threads.
      Interlocked::Increment( threadCount );
      
      // Wait on the EventWaitHandle.
      ewh->WaitOne();

      Console::WriteLine( L"Thread {0} exits.", data );
      // Decrement the count of blocked threads.
      Interlocked::Decrement( threadCount );
      
      // After signaling ewh, the main thread blocks on
      // clearCount until the signaled thread has
      // decremented the count. Signal it now.
      //
      clearCount->Set();
   }
};
using System;
using System.Threading;

public class Example
{
    // The EventWaitHandle used to demonstrate the difference
    // between AutoReset and ManualReset synchronization events.
    //
    private static EventWaitHandle ewh;

    // A counter to make sure all threads are started and
    // blocked before any are released. A Long is used to show
    // the use of the 64-bit Interlocked methods.
    //
    private static long threadCount = 0;

    // An AutoReset event that allows the main thread to block
    // until an exiting thread has decremented the count.
    //
    private static EventWaitHandle clearCount = 
        new EventWaitHandle(false, EventResetMode.AutoReset);

    [MTAThread]
    public static void Main()
    {
        // Create an AutoReset EventWaitHandle.
        //
        ewh = new EventWaitHandle(false, EventResetMode.AutoReset);

        // Create and start five numbered threads. Use the
        // ParameterizedThreadStart delegate, so the thread
        // number can be passed as an argument to the Start 
        // method.
        for (int i = 0; i <= 4; i++)
        {
            Thread t = new Thread(
                new ParameterizedThreadStart(ThreadProc)
            );
            t.Start(i);
        }

        // Wait until all the threads have started and blocked.
        // When multiple threads use a 64-bit value on a 32-bit
        // system, you must access the value through the
        // Interlocked class to guarantee thread safety.
        //
        while (Interlocked.Read(ref threadCount) < 5)
        {
            Thread.Sleep(500);
        }

        // Release one thread each time the user presses ENTER,
        // until all threads have been released.
        //
        while (Interlocked.Read(ref threadCount) > 0)
        {
            Console.WriteLine("Press ENTER to release a waiting thread.");
            Console.ReadLine();

            // SignalAndWait signals the EventWaitHandle, which
            // releases exactly one thread before resetting, 
            // because it was created with AutoReset mode. 
            // SignalAndWait then blocks on clearCount, to 
            // allow the signaled thread to decrement the count
            // before looping again.
            //
            WaitHandle.SignalAndWait(ewh, clearCount);
        }
        Console.WriteLine();

        // Create a ManualReset EventWaitHandle.
        //
        ewh = new EventWaitHandle(false, EventResetMode.ManualReset);

        // Create and start five more numbered threads.
        //
        for(int i=0; i<=4; i++)
        {
            Thread t = new Thread(
                new ParameterizedThreadStart(ThreadProc)
            );
            t.Start(i);
        }

        // Wait until all the threads have started and blocked.
        //
        while (Interlocked.Read(ref threadCount) < 5)
        {
            Thread.Sleep(500);
        }

        // Because the EventWaitHandle was created with
        // ManualReset mode, signaling it releases all the
        // waiting threads.
        //
        Console.WriteLine("Press ENTER to release the waiting threads.");
        Console.ReadLine();
        ewh.Set();
    }

    public static void ThreadProc(object data)
    {
        int index = (int) data;

        Console.WriteLine("Thread {0} blocks.", data);
        // Increment the count of blocked threads.
        Interlocked.Increment(ref threadCount);

        // Wait on the EventWaitHandle.
        ewh.WaitOne();

        Console.WriteLine("Thread {0} exits.", data);
        // Decrement the count of blocked threads.
        Interlocked.Decrement(ref threadCount);

        // After signaling ewh, the main thread blocks on
        // clearCount until the signaled thread has 
        // decremented the count. Signal it now.
        //
        clearCount.Set();
    }
}
Imports System.Threading

Public Class Example

    ' The EventWaitHandle used to demonstrate the difference
    ' between AutoReset and ManualReset synchronization events.
    '
    Private Shared ewh As EventWaitHandle

    ' A counter to make sure all threads are started and
    ' blocked before any are released. A Long is used to show
    ' the use of the 64-bit Interlocked methods.
    '
    Private Shared threadCount As Long = 0

    ' An AutoReset event that allows the main thread to block
    ' until an exiting thread has decremented the count.
    '
    Private Shared clearCount As New EventWaitHandle(False, _
        EventResetMode.AutoReset)

    <MTAThread> _
    Public Shared Sub Main()

        ' Create an AutoReset EventWaitHandle.
        '
        ewh = New EventWaitHandle(False, EventResetMode.AutoReset)

        ' Create and start five numbered threads. Use the
        ' ParameterizedThreadStart delegate, so the thread
        ' number can be passed as an argument to the Start 
        ' method.
        For i As Integer = 0 To 4
            Dim t As New Thread(AddressOf ThreadProc)
            t.Start(i)
        Next i

        ' Wait until all the threads have started and blocked.
        ' When multiple threads use a 64-bit value on a 32-bit
        ' system, you must access the value through the
        ' Interlocked class to guarantee thread safety.
        '
        While Interlocked.Read(threadCount) < 5
            Thread.Sleep(500)
        End While

        ' Release one thread each time the user presses ENTER,
        ' until all threads have been released.
        '
        While Interlocked.Read(threadCount) > 0
            Console.WriteLine("Press ENTER to release a waiting thread.")
            Console.ReadLine()

            ' SignalAndWait signals the EventWaitHandle, which
            ' releases exactly one thread before resetting, 
            ' because it was created with AutoReset mode. 
            ' SignalAndWait then blocks on clearCount, to 
            ' allow the signaled thread to decrement the count
            ' before looping again.
            '
            WaitHandle.SignalAndWait(ewh, clearCount)
        End While
        Console.WriteLine()

        ' Create a ManualReset EventWaitHandle.
        '
        ewh = New EventWaitHandle(False, EventResetMode.ManualReset)

        ' Create and start five more numbered threads.
        '
        For i As Integer = 0 To 4
            Dim t As New Thread(AddressOf ThreadProc)
            t.Start(i)
        Next i

        ' Wait until all the threads have started and blocked.
        '
        While Interlocked.Read(threadCount) < 5
            Thread.Sleep(500)
        End While

        ' Because the EventWaitHandle was created with
        ' ManualReset mode, signaling it releases all the
        ' waiting threads.
        '
        Console.WriteLine("Press ENTER to release the waiting threads.")
        Console.ReadLine()
        ewh.Set()
        
    End Sub

    Public Shared Sub ThreadProc(ByVal data As Object)
        Dim index As Integer = CInt(data)

        Console.WriteLine("Thread {0} blocks.", data)
        ' Increment the count of blocked threads.
        Interlocked.Increment(threadCount)

        ' Wait on the EventWaitHandle.
        ewh.WaitOne()

        Console.WriteLine("Thread {0} exits.", data)
        ' Decrement the count of blocked threads.
        Interlocked.Decrement(threadCount)

        ' After signaling ewh, the main thread blocks on
        ' clearCount until the signaled thread has 
        ' decremented the count. Signal it now.
        '
        clearCount.Set()
    End Sub
End Class

注釈

イベントの初期状態が非署名の場合、イベントを待機するスレッドはブロックされます。 初期状態が通知され、 ManualReset フラグが に mode指定されている場合、イベントを待機するスレッドはブロックされません。 初期状態が 通知され、 が のAutoReset場合、modeイベントを待機する最初のスレッドが直ちに解放され、その後イベントがリセットされ、後続のスレッドがブロックされます。

こちらもご覧ください

適用対象

EventWaitHandle(Boolean, EventResetMode, String)

ソース:
EventWaitHandle.cs
ソース:
EventWaitHandle.cs
ソース:
EventWaitHandle.cs

この呼び出しの結果として待機ハンドルが作成された場合に待機ハンドルの初期状態をシグナル状態に設定するかどうか、待機ハンドルが自動的にリセットされるかまたは手動でリセットされるか、およびシステムの同期イベントの名前を指定して、EventWaitHandle クラスの新しいインスタンスを初期化します。

public:
 EventWaitHandle(bool initialState, System::Threading::EventResetMode mode, System::String ^ name);
[System.Security.SecurityCritical]
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string? name);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name);
[<System.Security.SecurityCritical>]
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string -> System.Threading.EventWaitHandle
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string -> System.Threading.EventWaitHandle
Public Sub New (initialState As Boolean, mode As EventResetMode, name As String)

パラメーター

initialState
Boolean

名前の付いたイベントがこの呼び出しの結果として作成された場合に、初期状態をシグナル状態に設定するには true、非シグナル状態に設定するには false

mode
EventResetMode

イベントが自動的にリセットされるかまたは手動でリセットされるかを指定する EventResetMode 値の 1 つ。

name
String

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

属性

例外

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

または

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

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

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

アクセス制御セキュリティを使用した名前付きイベントが存在しますが、ユーザーに FullControl がありません。

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

mode 列挙値が適正範囲外でした。

または

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

注釈

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

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

パラメーターに指定された名前のシステム イベントが既に name 存在する場合、 initialState パラメーターは無視されます。

注意事項

既定では、名前付きイベントは、そのイベントを作成したユーザーに限定されません。 他のユーザーは、イベントを不適切に設定またはリセットすることによってイベントを妨害するなど、イベントを開いて使用できる場合があります。 特定のユーザーへのアクセスを制限するには、コンストラクター オーバーロードを使用するか EventWaitHandleAcl 、名前付きイベントを作成するときに を EventWaitHandleSecurity 渡します。 信頼されていないユーザーがコードを実行している可能性があるシステムでは、アクセス制限なしで名前付きイベントを使用しないでください。

重要

名前付きシステム イベントにこのコンストラクターを使用する場合は、 に を指定 false します initialState。 このコンストラクターでは、名前付きシステム イベントが作成されたかどうかを判断する方法がないため、名前付きイベントの状態を想定することはできません。 名前付きイベントが作成されたかどうかを判断するには、コンストラクターまたは コンストラクターをEventWaitHandle(Boolean, EventResetMode, String, Boolean, EventWaitHandleSecurity)使用EventWaitHandle(Boolean, EventResetMode, String, Boolean)します。

イベントの初期状態が非署名の場合、イベントを待機するスレッドはブロックされます。 初期状態が通知され、 ManualReset フラグが に mode指定されている場合、イベントを待機するスレッドはブロックされません。 初期状態が 通知され、 が のAutoReset場合、modeイベントを待機する最初のスレッドが直ちに解放され、その後イベントがリセットされ、後続のスレッドがブロックされます。

こちらもご覧ください

適用対象

EventWaitHandle(Boolean, EventResetMode, String, Boolean)

ソース:
EventWaitHandle.cs
ソース:
EventWaitHandle.cs
ソース:
EventWaitHandle.cs

EventWaitHandle クラスの新しいインスタンスを初期化し、待機ハンドルがこの呼び出しの結果として作成された場合に最初にシグナル状態になるかどうか、リセットは自動または手動か、システムの同期イベントの名前、呼び出しの後の値で名前の付いたシステム イベントが作成されたかどうかを示すブール値変数を指定します。

public:
 EventWaitHandle(bool initialState, System::Threading::EventResetMode mode, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew);
[System.Security.SecurityCritical]
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name, out bool createdNew);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string? name, out bool createdNew);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name, out bool createdNew);
[<System.Security.SecurityCritical>]
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string * bool -> System.Threading.EventWaitHandle
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string * bool -> System.Threading.EventWaitHandle
Public Sub New (initialState As Boolean, mode As EventResetMode, name As String, ByRef createdNew As Boolean)

パラメーター

initialState
Boolean

名前の付いたイベントがこの呼び出しの結果として作成された場合に、初期状態をシグナル状態に設定するには true、非シグナル状態に設定するには false

mode
EventResetMode

イベントが自動的にリセットされるかまたは手動でリセットされるかを指定する EventResetMode 値の 1 つ。

name
String

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

createdNew
Boolean

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

属性

例外

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

または

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

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

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

アクセス制御セキュリティを使用した名前付きイベントが存在しますが、ユーザーに FullControl がありません。

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

mode 列挙値が適正範囲外でした。

または

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

注釈

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

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

パラメーターに指定された名前のシステム イベントが既に name 存在する場合、 initialState パラメーターは無視されます。 このコンストラクターを呼び出した後、 パラメーター (ByRef Visual Basic のパラメーター)createdNew に指定されたref変数の値を使用して、名前付きシステム イベントが既に存在するか、作成されたかを判断します。

イベントの初期状態が未署名の場合、イベントを待機するスレッドはブロックされます。 初期状態がシグナル化され ManualReset 、 フラグが に mode指定されている場合、イベントを待機するスレッドはブロックされません。 初期状態が シグナル化され mode 、 が の AutoReset場合は、イベントを待機する最初のスレッドが直ちに解放され、その後イベントがリセットされ、後続のスレッドがブロックされます。

注意事項

既定では、名前付きイベントは、それを作成したユーザーに制限されません。 他のユーザーは、イベントを不適切に設定またはリセットすることによってイベントを妨害するなど、イベントを開いて使用できる場合があります。 特定のユーザーへのアクセスを制限するには、コンストラクターのオーバーロードを使用するか EventWaitHandleAcl 、名前付きイベントを作成するときに を EventWaitHandleSecurity 渡します。 信頼されていないユーザーがコードを実行している可能性があるシステムでは、アクセス制限なしで名前付きイベントを使用しないでください。

こちらもご覧ください

適用対象

EventWaitHandle(Boolean, EventResetMode, String, Boolean, EventWaitHandleSecurity)

EventWaitHandle クラスの新しいインスタンスを初期化し、待機ハンドルがこの呼び出しの結果として作成された場合に最初にシグナル状態になるかどうか、リセットは自動または手動か、システムの同期イベントの名前、呼び出しの後の値で名前の付いたシステム イベントが作成されたかどうかを示すブール値変数、および名前の付いたシステム イベントが作成された場合は、そのイベントにアクセス制御セキュリティを適用するかどうかを指定します。

public:
 EventWaitHandle(bool initialState, System::Threading::EventResetMode mode, System::String ^ name, [Runtime::InteropServices::Out] bool % createdNew, System::Security::AccessControl::EventWaitHandleSecurity ^ eventSecurity);
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name, out bool createdNew, System.Security.AccessControl.EventWaitHandleSecurity eventSecurity);
[System.Security.SecurityCritical]
public EventWaitHandle (bool initialState, System.Threading.EventResetMode mode, string name, out bool createdNew, System.Security.AccessControl.EventWaitHandleSecurity eventSecurity);
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string * bool * System.Security.AccessControl.EventWaitHandleSecurity -> System.Threading.EventWaitHandle
[<System.Security.SecurityCritical>]
new System.Threading.EventWaitHandle : bool * System.Threading.EventResetMode * string * bool * System.Security.AccessControl.EventWaitHandleSecurity -> System.Threading.EventWaitHandle
Public Sub New (initialState As Boolean, mode As EventResetMode, name As String, ByRef createdNew As Boolean, eventSecurity As EventWaitHandleSecurity)

パラメーター

initialState
Boolean

名前の付いたイベントがこの呼び出しの結果として作成された場合に、初期状態をシグナル状態に設定するには true、非シグナル状態に設定するには false

mode
EventResetMode

イベントが自動的にリセットされるかまたは手動でリセットされるかを指定する EventResetMode 値の 1 つ。

name
String

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

createdNew
Boolean

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

eventSecurity
EventWaitHandleSecurity

名前付きシステム イベントに適用するアクセス制御セキュリティを表す EventWaitHandleSecurity オブジェクト。

属性

例外

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

または

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

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

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

アクセス制御セキュリティを使用した名前付きイベントが存在しますが、ユーザーに FullControl がありません。

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

mode 列挙値が適正範囲外でした。

または

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

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

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

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

アクセス許可が変更されると、イベントを待機して通知するために必要な権限でイベントが開かれます。 3 番目のコマンド ウィンドウからコンパイルされた例を実行した場合、この例は新しいアクセス許可を使用して実行されます。

using namespace System;
using namespace System::Threading;
using namespace System::Security::AccessControl;
using namespace System::Security::Permissions;

public ref class Example
{
public:
   [SecurityPermissionAttribute(SecurityAction::Demand,Flags=SecurityPermissionFlag::UnmanagedCode)]
   static void Main()
   {
      String^ ewhName = L"EventWaitHandleExample5";

      EventWaitHandle^ ewh = nullptr;
      bool doesNotExist = false;
      bool unauthorized = false;
      
      // The value of this variable is set by the event
      // constructor. It is true if the named system event was
      // created, and false if the named event already existed.
      //
      bool wasCreated;
      
      // Attempt to open the named event.
      try
      {
         // Open the event with (EventWaitHandleRights.Synchronize
         // | EventWaitHandleRights.Modify), to wait on and
         // signal the named event.
         //
         ewh = EventWaitHandle::OpenExisting( ewhName );
      }
      catch ( WaitHandleCannotBeOpenedException^ ) 
      {
         Console::WriteLine( L"Named event does not exist." );
         doesNotExist = true;
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message );
         unauthorized = true;
      }

      // There are three cases: (1) The event does not exist.
      // (2) The event exists, but the current user doesn't
      // have access. (3) The event exists and the user has
      // access.
      //
      if ( doesNotExist )
      {
         // The event does not exist, so create it.

         // Create an access control list (ACL) that denies the
         // current user the right to wait on or signal the
         // event, but allows the right to read and change
         // security information for the event.
         //
         String^ user = String::Concat( Environment::UserDomainName, L"\\",
            Environment::UserName );
         EventWaitHandleSecurity^ ewhSec = gcnew EventWaitHandleSecurity;
         //following constructor fails
         EventWaitHandleAccessRule^ rule = gcnew EventWaitHandleAccessRule(
            user,
            static_cast<EventWaitHandleRights>(
               EventWaitHandleRights::Synchronize | 
               EventWaitHandleRights::Modify),
            AccessControlType::Deny );
         ewhSec->AddAccessRule( rule );

         rule = gcnew EventWaitHandleAccessRule( user,
            static_cast<EventWaitHandleRights>(
               EventWaitHandleRights::ReadPermissions | 
               EventWaitHandleRights::ChangePermissions),
            AccessControlType::Allow );
         ewhSec->AddAccessRule( rule );
         
         // Create an EventWaitHandle object that represents
         // the system event named by the constant 'ewhName',
         // initially signaled, with automatic reset, and with
         // the specified security access. The Boolean value that
         // indicates creation of the underlying system object
         // is placed in wasCreated.
         //
         ewh = gcnew EventWaitHandle( true,
            EventResetMode::AutoReset,
            ewhName,
            wasCreated,
            ewhSec );
         
         // If the named system event was created, it can be
         // used by the current instance of this program, even
         // though the current user is denied access. The current
         // program owns the event. Otherwise, exit the program.
         //
         if ( wasCreated )
         {
            Console::WriteLine( L"Created the named event." );
         }
         else
         {
            Console::WriteLine( L"Unable to create the event." );
            return;
         }
      }
      else if ( unauthorized )
      {
         // Open the event to read and change the access control
         // security. The access control security defined above
         // allows the current user to do this.
         //
         try
         {
            ewh = EventWaitHandle::OpenExisting( ewhName, 
               static_cast<EventWaitHandleRights>(
                  EventWaitHandleRights::ReadPermissions |
                  EventWaitHandleRights::ChangePermissions) );
            
            // Get the current ACL. This requires
            // EventWaitHandleRights.ReadPermissions.
            EventWaitHandleSecurity^ ewhSec = ewh->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 event must
            // be removed.
            EventWaitHandleAccessRule^ rule = gcnew EventWaitHandleAccessRule(
               user,
               static_cast<EventWaitHandleRights>(
                  EventWaitHandleRights::Synchronize |
                  EventWaitHandleRights::Modify),
               AccessControlType::Deny );
            ewhSec->RemoveAccessRule( rule );
            
            // Now grant the user the correct rights.
            //
            rule = gcnew EventWaitHandleAccessRule( user,
               static_cast<EventWaitHandleRights>(
                  EventWaitHandleRights::Synchronize |
                  EventWaitHandleRights::Modify),
               AccessControlType::Allow );
            ewhSec->AddAccessRule( rule );
            
            // Update the ACL. This requires
            // EventWaitHandleRights.ChangePermissions.
            ewh->SetAccessControl( ewhSec );
            Console::WriteLine( L"Updated event security." );
            
            // Open the event with (EventWaitHandleRights.Synchronize
            // | EventWaitHandleRights.Modify), the rights required
            // to wait on and signal the event.
            //
            ewh = EventWaitHandle::OpenExisting( ewhName );
         }
         catch ( UnauthorizedAccessException^ ex ) 
         {
            Console::WriteLine( L"Unable to change permissions: {0}",
               ex->Message );
            return;
         }

      }
      
      // Wait on the event, and hold it until the program
      // exits.
      //
      try
      {
         Console::WriteLine( L"Wait on the event." );
         ewh->WaitOne();
         Console::WriteLine( L"Event was signaled." );
         Console::WriteLine( L"Press the Enter key to signal the event and exit." );
         Console::ReadLine();
      }
      catch ( UnauthorizedAccessException^ ex ) 
      {
         Console::WriteLine( L"Unauthorized access: {0}", ex->Message );
      }
      finally
      {
         ewh->Set();
      }
   }
};

int main()
{
   Example::Main();
}
using System;
using System.Threading;
using System.Security.AccessControl;

internal class Example
{
    internal static void Main()
    {
        const string ewhName = "EventWaitHandleExample5";

        EventWaitHandle ewh = null;
        bool doesNotExist = false;
        bool unauthorized = false;

        // The value of this variable is set by the event
        // constructor. It is true if the named system event was
        // created, and false if the named event already existed.
        //
        bool wasCreated;

        // Attempt to open the named event.
        try
        {
            // Open the event with (EventWaitHandleRights.Synchronize
            // | EventWaitHandleRights.Modify), to wait on and 
            // signal the named event.
            //
            ewh = EventWaitHandle.OpenExisting(ewhName);
        }
        catch (WaitHandleCannotBeOpenedException)
        {
            Console.WriteLine("Named event does not exist.");
            doesNotExist = true;
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
            unauthorized = true;
        }

        // There are three cases: (1) The event does not exist.
        // (2) The event exists, but the current user doesn't 
        // have access. (3) The event exists and the user has
        // access.
        //
        if (doesNotExist)
        {
            // The event does not exist, so create it.

            // Create an access control list (ACL) that denies the
            // current user the right to wait on or signal the 
            // event, but allows the right to read and change
            // security information for the event.
            //
            string user = Environment.UserDomainName + "\\"
                + Environment.UserName;
            EventWaitHandleSecurity ewhSec = 
                new EventWaitHandleSecurity();

            EventWaitHandleAccessRule rule = 
                new EventWaitHandleAccessRule(user, 
                    EventWaitHandleRights.Synchronize | 
                    EventWaitHandleRights.Modify, 
                    AccessControlType.Deny);
            ewhSec.AddAccessRule(rule);

            rule = new EventWaitHandleAccessRule(user, 
                EventWaitHandleRights.ReadPermissions | 
                EventWaitHandleRights.ChangePermissions, 
                AccessControlType.Allow);
            ewhSec.AddAccessRule(rule);

            // Create an EventWaitHandle object that represents
            // the system event named by the constant 'ewhName', 
            // initially signaled, with automatic reset, and with
            // the specified security access. The Boolean value that 
            // indicates creation of the underlying system object
            // is placed in wasCreated.
            //
            ewh = new EventWaitHandle(true, 
                EventResetMode.AutoReset, 
                ewhName, 
                out wasCreated, 
                ewhSec);

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

                // Get the current ACL. This requires 
                // EventWaitHandleRights.ReadPermissions.
                EventWaitHandleSecurity ewhSec = ewh.GetAccessControl();
                
                string user = Environment.UserDomainName + "\\"
                    + Environment.UserName;

                // First, the rule that denied the current user 
                // the right to enter and release the event must
                // be removed.
                EventWaitHandleAccessRule rule = 
                    new EventWaitHandleAccessRule(user, 
                        EventWaitHandleRights.Synchronize | 
                        EventWaitHandleRights.Modify, 
                        AccessControlType.Deny);
                ewhSec.RemoveAccessRule(rule);

                // Now grant the user the correct rights.
                // 
                rule = new EventWaitHandleAccessRule(user, 
                    EventWaitHandleRights.Synchronize | 
                    EventWaitHandleRights.Modify, 
                    AccessControlType.Allow);
                ewhSec.AddAccessRule(rule);

                // Update the ACL. This requires
                // EventWaitHandleRights.ChangePermissions.
                ewh.SetAccessControl(ewhSec);

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

                // Open the event with (EventWaitHandleRights.Synchronize 
                // | EventWaitHandleRights.Modify), the rights required
                // to wait on and signal the event.
                //
                ewh = EventWaitHandle.OpenExisting(ewhName);
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine("Unable to change permissions: {0}",
                    ex.Message);
                return;
            }
        }

        // Wait on the event, and hold it until the program
        // exits.
        //
        try
        {
            Console.WriteLine("Wait on the event.");
            ewh.WaitOne();
            Console.WriteLine("Event was signaled.");
            Console.WriteLine("Press the Enter key to signal the event and exit.");
            Console.ReadLine();
        }
        catch (UnauthorizedAccessException ex)
        {
            Console.WriteLine("Unauthorized access: {0}", ex.Message);
        }
        finally
        {
            ewh.Set();
        }
    }
}
Imports System.Threading
Imports System.Security.AccessControl

Friend Class Example

    <MTAThread> _
    Friend Shared Sub Main()
        Const ewhName As String = "EventWaitHandleExample5"

        Dim ewh As EventWaitHandle = Nothing
        Dim doesNotExist as Boolean = False
        Dim unauthorized As Boolean = False

        ' The value of this variable is set by the event
        ' constructor. It is True if the named system event was
        ' created, and False if the named event already existed.
        '
        Dim wasCreated As Boolean

        ' Attempt to open the named event.
        Try
            ' Open the event with (EventWaitHandleRights.Synchronize
            ' Or EventWaitHandleRights.Modify), to wait on and 
            ' signal the named event.
            '
            ewh = EventWaitHandle.OpenExisting(ewhName)
        Catch ex As WaitHandleCannotBeOpenedException
            Console.WriteLine("Named event 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 event does not exist.
        ' (2) The event exists, but the current user doesn't 
        ' have access. (3) The event exists and the user has
        ' access.
        '
        If doesNotExist Then
            ' The event does not exist, so create it.

            ' Create an access control list (ACL) that denies the
            ' current user the right to wait on or signal the 
            ' event, but allows the right to read and change
            ' security information for the event.
            '
            Dim user As String = Environment.UserDomainName _ 
                & "\" & Environment.UserName
            Dim ewhSec As New EventWaitHandleSecurity()

            Dim rule As New EventWaitHandleAccessRule(user, _
                EventWaitHandleRights.Synchronize Or _
                EventWaitHandleRights.Modify, _
                AccessControlType.Deny)
            ewhSec.AddAccessRule(rule)

            rule = New EventWaitHandleAccessRule(user, _
                EventWaitHandleRights.ReadPermissions Or _
                EventWaitHandleRights.ChangePermissions, _
                AccessControlType.Allow)
            ewhSec.AddAccessRule(rule)

            ' Create an EventWaitHandle object that represents
            ' the system event named by the constant 'ewhName', 
            ' initially signaled, with automatic reset, and with
            ' the specified security access. The Boolean value that 
            ' indicates creation of the underlying system object
            ' is placed in wasCreated.
            '
            ewh = New EventWaitHandle(True, _
                EventResetMode.AutoReset, ewhName, _
                wasCreated, ewhSec)

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

        ElseIf unauthorized Then

            ' Open the event to read and change the access control
            ' security. The access control security defined above
            ' allows the current user to do this.
            '
            Try
                ewh = EventWaitHandle.OpenExisting(ewhName, _
                    EventWaitHandleRights.ReadPermissions Or _
                    EventWaitHandleRights.ChangePermissions)

                ' Get the current ACL. This requires 
                ' EventWaitHandleRights.ReadPermissions.
                Dim ewhSec As EventWaitHandleSecurity = _
                    ewh.GetAccessControl()
                
                Dim user As String = Environment.UserDomainName _ 
                    & "\" & Environment.UserName

                ' First, the rule that denied the current user 
                ' the right to enter and release the event must
                ' be removed.
                Dim rule As New EventWaitHandleAccessRule(user, _
                    EventWaitHandleRights.Synchronize Or _
                    EventWaitHandleRights.Modify, _
                    AccessControlType.Deny)
                ewhSec.RemoveAccessRule(rule)

                ' Now grant the user the correct rights.
                ' 
                rule = New EventWaitHandleAccessRule(user, _
                    EventWaitHandleRights.Synchronize Or _
                    EventWaitHandleRights.Modify, _
                    AccessControlType.Allow)
                ewhSec.AddAccessRule(rule)

                ' Update the ACL. This requires
                ' EventWaitHandleRights.ChangePermissions.
                ewh.SetAccessControl(ewhSec)

                Console.WriteLine("Updated event security.")

                ' Open the event with (EventWaitHandleRights.Synchronize 
                ' Or EventWaitHandleRights.Modify), the rights required
                ' to wait on and signal the event.
                '
                ewh = EventWaitHandle.OpenExisting(ewhName)

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

        End If

        ' Wait on the event, and hold it until the program
        ' exits.
        '
        Try
            Console.WriteLine("Wait on the event.")
            ewh.WaitOne()
            Console.WriteLine("Event was signaled.")
            Console.WriteLine("Press the Enter key to signal the event and exit.")
            Console.ReadLine()
        Catch ex As UnauthorizedAccessException
            Console.WriteLine("Unauthorized access: {0}", _
                ex.Message)
        Finally
            ewh.Set()
        End Try
    End Sub 
End Class

注釈

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

このコンストラクターは、システム イベントを EventWaitHandle 表す オブジェクトを初期化します。 同じシステム イベントを表す複数 EventWaitHandle のオブジェクトを作成できます。

システム イベントが存在しない場合は、指定されたアクセス制御セキュリティを使用して作成されます。 イベントが存在する場合、指定されたアクセス制御のセキュリティは無視されます。

Note

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

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

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

パラメーターに指定された名前のシステム イベントが既に name 存在する場合、 initialState パラメーターは無視されます。 このコンストラクターを呼び出した後、 パラメーター (ByRef Visual Basic のパラメーター) createdNew に指定されたref変数の値を使用して、名前付きシステム イベントが既に存在するか、作成されたかを判断します。

イベントの初期状態が未署名の場合、イベントを待機するスレッドはブロックされます。 初期状態がシグナル化され ManualReset 、 フラグが に mode指定されている場合、イベントを待機するスレッドはブロックされません。 初期状態が シグナル化され mode 、 が の AutoReset場合は、イベントを待機する最初のスレッドが直ちに解放され、その後イベントがリセットされ、後続のスレッドがブロックされます。

注意事項

既定では、名前付きイベントは、それを作成したユーザーに制限されません。 他のユーザーは、イベントを不適切に設定またはリセットすることによってイベントを妨害するなど、イベントを開いて使用できる場合があります。 特定のユーザーへのアクセスを制限するために、名前付きイベントを作成するときに を渡 EventWaitHandleSecurity すことができます。 信頼されていないユーザーがコードを実行している可能性があるシステムでは、アクセス制限なしで名前付きイベントを使用しないでください。

こちらもご覧ください

適用対象