EventWaitHandleとは? わかりやすく解説

EventWaitHandle クラス

メモ : このクラスは、.NET Framework version 2.0新しく追加されたものです。

スレッドの同期イベント表します

名前空間: System.Threading
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

<ComVisibleAttribute(True)> _
Public Class EventWaitHandle
    Inherits WaitHandle
Dim instance As EventWaitHandle
[ComVisibleAttribute(true)] 
public class EventWaitHandle : WaitHandle
[ComVisibleAttribute(true)] 
public ref class EventWaitHandle : public
 WaitHandle
/** @attribute ComVisibleAttribute(true) */ 
public class EventWaitHandle extends WaitHandle
ComVisibleAttribute(true) 
public class EventWaitHandle extends
 WaitHandle
解説解説
メモメモ

このクラス適用される HostProtectionAttribute 属性Resources プロパティの値は、Synchronization または ExternalThreading です。HostProtectionAttribute は、デスクトップ アプリケーション (一般的にはアイコンダブルクリックコマンド入力、またはブラウザURL入力して起動するアプリケーション) には影響しません。詳細については、HostProtectionAttribute クラストピックまたは「SQL Server プログラミングホスト保護属性」を参照してください

EventWaitHandle クラス使用すると、スレッドシグナル通じて相互に通信できます通常EventWaitHandle では、ブロックされていないスレッドSet メソッド呼び出して 1 つ上のブロックされスレッド解放するまでの間、1 つ上のスレッドブロックされます。スレッドは、static (Visual Basic では Shared) のSystem.Threading.WaitHandle.SignalAndWait メソッド呼び出すことにより、分割不可能な操作としてEventWaitHandleシグナル通知してからブロックされます。

シグナル状態になった EventWaitHandle動作は、リセット モード依存します。EventResetMode.AutoReset フラグ指定して作成されEventWaitHandleシグナル状態になっている場合は、待機中のスレッド1 つ解放した後で自動的にリセットされます。EventResetMode.ManualReset フラグ指定して作成されEventWaitHandleシグナル状態になっている場合は、対応する Reset メソッド呼び出されるまでシグナル状態のままとなります

自動リセット イベントは、リソースへの排他的なアクセス提供します待機しているスレッドがないときに自動リセット イベントシグナル状態になっている場合は、1 つスレッド待機試みるまでシグナル状態のままとなります。このイベントスレッド解放した直後リセットされ後続スレッドブロックします

手動リセットゲートのようなものです。イベントシグナル状態でないときは、イベント待機しているスレッドブロックされます。イベントシグナル状態になっているときは、待機中のすべてのスレッド解放され対応する Reset メソッド呼び出されるまでイベントシグナル状態のままになります (つまり、後続待機スレッドブロックされません)。手動リセット イベントは、1 つスレッドが処理を完了しないと他のスレッド続行できない場合に便利です。

EventWaitHandle オブジェクトは、static (Visual Basic では Shared) の System.Threading.WaitHandle.WaitAll メソッドおよび System.Threading.WaitHandle.WaitAny メソッド組み合わせて使用できます

スレッドの同期機構詳細については、「EventWaitHandle、AutoResetEvent、および ManualResetEvent」を参照してください

使用例使用例

SignalAndWait(WaitHandle,WaitHandle) メソッド オーバーロード使用してメイン スレッドブロックされているスレッドシグナル送信し、そのスレッドタスク完了するまで待機できるようにするコード例次に示します

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

Imports System
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
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();
    }
}
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();
   }
};
import System.*;
import 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);

    /** @attribute MTAThread()
     */
    public static void main(String[]
 args)
    {
        // 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++) {
            System.Threading.Thread t = new System.Threading.Thread(new
 
                ParameterizedThreadStart(ThreadProc));
            t.Start((Int32)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) {
            System.Threading.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("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++) {
            System.Threading.Thread t = new System.Threading.Thread(new
 
                ParameterizedThreadStart(ThreadProc));
            t.Start((Int32)i);
        }
        // Wait until all the threads have started and blocked.
        //
        while (Interlocked.Read(threadCount) < 5) {
            System.Threading.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();
    } //main

    public static void ThreadProc(Object
 data)
    {
        int index = System.Convert.ToInt32(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();
    } //ThreadProc
} //Example
継承階層継承階層
System.Object
   System.MarshalByRefObject
     System.Threading.WaitHandle
      System.Threading.EventWaitHandle
         System.Threading.AutoResetEvent
         System.Threading.ManualResetEvent
スレッド セーフスレッド セーフ
この型の public static (Visual Basic では Shared) メンバはすべて、スレッド セーフです。インスタンス メンバ場合は、スレッド セーフであるとは限りません。
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
EventWaitHandle メンバ
System.Threading 名前空間
WaitHandle
AutoResetEvent クラス
ManualResetEvent
その他の技術情報
マネージ スレッド処理
EventWaitHandle、AutoResetEvent、および ManualResetEvent

EventWaitHandle コンストラクタ (Boolean, EventResetMode, String)

メモ : このコンストラクタは、.NET Framework version 2.0新しく追加されたものです。

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

名前空間: System.Threading
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Sub New ( _
    initialState As Boolean, _
    mode As EventResetMode, _
    name As String _
)
Dim initialState As Boolean
Dim mode As EventResetMode
Dim name As String

Dim instance As New EventWaitHandle(initialState,
 mode, name)
public EventWaitHandle (
    bool initialState,
    EventResetMode mode,
    string name
)
public:
EventWaitHandle (
    bool initialState, 
    EventResetMode mode, 
    String^ name
)
public EventWaitHandle (
    boolean initialState, 
    EventResetMode mode, 
    String name
)
public function EventWaitHandle (
    initialState : boolean, 
    mode : EventResetMode, 
    name : String
)

パラメータ

initialState

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

mode

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

name

システム全体有効な同期イベントの名前。

例外例外
例外種類条件

IOException

Win32 エラー発生しました

UnauthorizedAccessException

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

WaitHandleCannotBeOpenedException

前付イベント作成できません。別の型の待機ハンドルに同じ名前が付けられていることが原因として考えられます。

ArgumentException

name260 文字超えてます。

解説解説

namenull 参照 (Visual Basic では Nothing) または空の文字列場合ローカル EventWaitHandle作成されます。

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

メモ重要 :

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

イベント初期状態が非シグナル状態の場合イベント待機するスレッドブロックされます。イベント初期状態シグナル状態で、ManualReset フラグmode指定されている場合イベント待機するスレッドブロックされません。イベント初期状態シグナル状態で、modeAutoReset である場合イベント待機している最初スレッドはすぐに解放されますが、その後イベントリセットされ後続スレッドブロックされます。

.NET Framework のセキュリティ.NET Frameworkセキュリティ
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
EventWaitHandle クラス
EventWaitHandle メンバ
System.Threading 名前空間
その他の技術情報
EventWaitHandle、AutoResetEvent、および ManualResetEvent

EventWaitHandle コンストラクタ (Boolean, EventResetMode)

メモ : このコンストラクタは、.NET Framework version 2.0新しく追加されたものです。

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

名前空間: System.Threading
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Sub New ( _
    initialState As Boolean, _
    mode As EventResetMode _
)
Dim initialState As Boolean
Dim mode As EventResetMode

Dim instance As New EventWaitHandle(initialState,
 mode)
public EventWaitHandle (
    bool initialState,
    EventResetMode mode
)
public:
EventWaitHandle (
    bool initialState, 
    EventResetMode mode
)
public EventWaitHandle (
    boolean initialState, 
    EventResetMode mode
)
public function EventWaitHandle (
    initialState : boolean, 
    mode : EventResetMode
)

パラメータ

initialState

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

mode

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

解説解説
使用例使用例

SignalAndWait(WaitHandle,WaitHandle) メソッド オーバーロード使用してメイン スレッドブロックされているスレッドシグナル送信し、そのスレッドタスク完了するまで待機できるようにするコード例次に示します

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

Imports System
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
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();
    }
}
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();
   }
};
import System.*;
import 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);

    /** @attribute MTAThread()
     */
    public static void main(String[]
 args)
    {
        // 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++) {
            System.Threading.Thread t = new System.Threading.Thread(new
 
                ParameterizedThreadStart(ThreadProc));
            t.Start((Int32)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) {
            System.Threading.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("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++) {
            System.Threading.Thread t = new System.Threading.Thread(new
 
                ParameterizedThreadStart(ThreadProc));
            t.Start((Int32)i);
        }
        // Wait until all the threads have started and blocked.
        //
        while (Interlocked.Read(threadCount) < 5) {
            System.Threading.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();
    } //main

    public static void ThreadProc(Object
 data)
    {
        int index = System.Convert.ToInt32(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();
    } //ThreadProc
} //Example
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
EventWaitHandle クラス
EventWaitHandle メンバ
System.Threading 名前空間
その他の技術情報
EventWaitHandle、AutoResetEvent、および ManualResetEvent

EventWaitHandle コンストラクタ (Boolean, EventResetMode, String, Boolean)

メモ : このコンストラクタは、.NET Framework version 2.0新しく追加されたものです。

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

名前空間: System.Threading
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Sub New ( _
    initialState As Boolean, _
    mode As EventResetMode, _
    name As String, _
    <OutAttribute> ByRef createdNew As
 Boolean _
)
Dim initialState As Boolean
Dim mode As EventResetMode
Dim name As String
Dim createdNew As Boolean

Dim instance As New EventWaitHandle(initialState,
 mode, name, createdNew)
public EventWaitHandle (
    bool initialState,
    EventResetMode mode,
    string name,
    out bool createdNew
)
public:
EventWaitHandle (
    bool initialState, 
    EventResetMode mode, 
    String^ name, 
    [OutAttribute] bool% createdNew
)
public EventWaitHandle (
    boolean initialState, 
    EventResetMode mode, 
    String name, 
    /** @attribute OutAttribute() */ /** @ref */ boolean createdNew
)
public function EventWaitHandle (
    initialState : boolean, 
    mode : EventResetMode, 
    name : String, 
    createdNew : boolean
)

パラメータ

initialState

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

mode

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

name

システム全体有効な同期イベントの名前。

createdNew

このメソッド返されるときに、呼び出し元のスレッドに名前付システム イベント初期所有権付与され場合true格納されます。それ以外場合false格納されます。このパラメータ初期化せずに渡されます。

例外例外
例外種類条件

IOException

Win32 エラー発生しました

UnauthorizedAccessException

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

WaitHandleCannotBeOpenedException

前付イベント作成できません。別の型の待機ハンドルに同じ名前が付けられていることが原因として考えられます。

ArgumentException

name260 文字超えてます。

解説解説
.NET Framework のセキュリティ.NET Frameworkセキュリティ
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
EventWaitHandle クラス
EventWaitHandle メンバ
System.Threading 名前空間
その他の技術情報
EventWaitHandle、AutoResetEvent、および ManualResetEvent

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 クラス
EventWaitHandle メンバ
System.Threading 名前空間

その他の技術情報

EventWaitHandle、AutoResetEvent、および ManualResetEvent

EventWaitHandle コンストラクタ (Boolean, EventResetMode, String, Boolean, EventWaitHandleSecurity)

メモ : このコンストラクタは、.NET Framework version 2.0新しく追加されたものです。

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

名前空間: System.Threading
アセンブリ: mscorlib (mscorlib.dll 内)
構文構文

Public Sub New ( _
    initialState As Boolean, _
    mode As EventResetMode, _
    name As String, _
    <OutAttribute> ByRef createdNew As
 Boolean, _
    eventSecurity As EventWaitHandleSecurity _
)
Dim initialState As Boolean
Dim mode As EventResetMode
Dim name As String
Dim createdNew As Boolean
Dim eventSecurity As EventWaitHandleSecurity

Dim instance As New EventWaitHandle(initialState,
 mode, name, createdNew, eventSecurity)
public EventWaitHandle (
    bool initialState,
    EventResetMode mode,
    string name,
    out bool createdNew,
    EventWaitHandleSecurity eventSecurity
)
public:
EventWaitHandle (
    bool initialState, 
    EventResetMode mode, 
    String^ name, 
    [OutAttribute] bool% createdNew, 
    EventWaitHandleSecurity^ eventSecurity
)
public EventWaitHandle (
    boolean initialState, 
    EventResetMode mode, 
    String name, 
    /** @attribute OutAttribute() */ /** @ref */ boolean createdNew, 
    EventWaitHandleSecurity eventSecurity
)
public function EventWaitHandle (
    initialState : boolean, 
    mode : EventResetMode, 
    name : String, 
    createdNew : boolean, 
    eventSecurity : EventWaitHandleSecurity
)

パラメータ

initialState

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

mode

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

name

システム全体有効な同期イベントの名前。

createdNew

このメソッド返されるときに、呼び出し元のスレッドに名前付システム イベント初期所有権付与され場合true格納されます。それ以外場合false格納されます。このパラメータ初期化せずに渡されます。

eventSecurity

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

例外例外
例外種類条件

IOException

Win32 エラー発生しました

UnauthorizedAccessException

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

WaitHandleCannotBeOpenedException

前付イベント作成できません。別の型の待機ハンドルに同じ名前が付けられていることが原因として考えられます。

ArgumentException

name260 文字超えてます。

解説解説

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

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

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

メモメモ

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

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

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

使用例使用例

アクセス制御セキュリティ使用した前付システム イベントプロセス間の動作デモンストレーションするコード例次に示します。この例では、OpenExisting(String) メソッド オーバーロード使用して、名前付イベント存在するかどうかテストしてます。

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

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

アクセス許可変更された後、待機シグナル通知必要な権限イベント開かれます。3 つ目のコマンド ウィンドウからコンパイル済みの例を実行する場合新しアクセス許可使用して実行されます。

Imports System
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 
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();
        }
    }
}
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();
}
.NET Framework のセキュリティ.NET Frameworkセキュリティ
プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照
関連項目
EventWaitHandle クラス
EventWaitHandle メンバ
System.Threading 名前空間
その他の技術情報
EventWaitHandle、AutoResetEvent、および ManualResetEvent

EventWaitHandle プロパティ


パブリック プロパティパブリック プロパティ

参照参照

関連項目

EventWaitHandle クラス
System.Threading 名前空間
WaitHandle
AutoResetEvent クラス
ManualResetEvent

その他の技術情報

マネージ スレッド処理
EventWaitHandle、AutoResetEvent、および ManualResetEvent

EventWaitHandle メソッド


パブリック メソッドパブリック メソッド

( プロテクト メソッド参照)
  名前 説明
パブリック メソッド Close  派生クラスオーバーライドされると、現在の WaitHandle で保持されているすべてのリソース解放します。 ( WaitHandle から継承されます。)
パブリック メソッド CreateObjRef  リモート オブジェクトとの通信使用するプロキシ生成必要な情報をすべて格納しているオブジェクト作成します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド Equals  オーバーロードされます2 つObject インスタンス等しかどうか判断します。 ( Object から継承されます。)
パブリック メソッド GetAccessControl 現在の EventWaitHandle オブジェクトによって表される前付システム イベントアクセス制御セキュリティを表す EventWaitHandleSecurity オブジェクト取得します
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用適してます。 ( Object から継承されます。)
パブリック メソッド GetLifetimeService  対象インスタンス有効期間ポリシー制御する現在の有効期間サービス オブジェクト取得します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド GetType  現在のインスタンスType取得します。 ( Object から継承されます。)
パブリック メソッド InitializeLifetimeService  対象インスタンス有効期間ポリシー制御する有効期間サービス オブジェクト取得します。 ( MarshalByRefObject から継承されます。)
パブリック メソッド OpenExisting オーバーロードされます既存の名前付同期イベント開きます
パブリック メソッド ReferenceEquals  指定した複数Object インスタンス同一かどうか判断します。 ( Object から継承されます。)
パブリック メソッド Reset イベントの状態を非シグナル状態に設定しスレッドブロックします
パブリック メソッド Set イベントの状態をシグナル状態に設定し待機している 1 つ上のスレッド進行できるようにします。
パブリック メソッド SetAccessControl 前付システム イベントアクセス制御セキュリティ設定します
パブリック メソッド SignalAndWait  オーバーロードされます分割不可能な操作として1 つWaitHandle通知し別の WaitHandle待機します。 ( WaitHandle から継承されます。)
パブリック メソッド ToString  現在の Object を表す String返します。 ( Object から継承されます。)
パブリック メソッド WaitAll  オーバーロードされます指定した配列内のすべての要素シグナル受信するまで待機します。 ( WaitHandle から継承されます。)
パブリック メソッド WaitAny  オーバーロードされます指定した配列内のいずれか要素シグナル受信するまで待機します。 ( WaitHandle から継承されます。)
パブリック メソッド WaitOne  オーバーロードされます派生クラスオーバーライドされると、現在の WaitHandleシグナル受信するまで現在のスレッドブロックします。 ( WaitHandle から継承されます。)
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

EventWaitHandle クラス
System.Threading 名前空間
WaitHandle
AutoResetEvent クラス
ManualResetEvent

その他の技術情報

マネージ スレッド処理
EventWaitHandle、AutoResetEvent、および ManualResetEvent

EventWaitHandle メンバ

スレッドの同期イベント表します

EventWaitHandle データ型公開されるメンバを以下の表に示します


パブリック コンストラクタパブリック コンストラクタ
パブリック プロパティパブリック プロパティ
パブリック メソッドパブリック メソッド
( プロテクト メソッド参照)
  名前 説明
パブリック メソッド Close  派生クラスオーバーライドされると、現在の WaitHandle で保持されているすべてのリソース解放します。 (WaitHandle から継承されます。)
パブリック メソッド CreateObjRef  リモート オブジェクトとの通信使用するプロキシ生成必要な情報をすべて格納しているオブジェクト作成します。 (MarshalByRefObject から継承されます。)
パブリック メソッド Equals  オーバーロードされます2 つObject インスタンス等しかどうか判断します。 (Object から継承されます。)
パブリック メソッド GetAccessControl 現在の EventWaitHandle オブジェクトによって表される前付システム イベントアクセス制御セキュリティを表す EventWaitHandleSecurity オブジェクト取得します
パブリック メソッド GetHashCode  特定の型のハッシュ関数として機能します。GetHashCode は、ハッシュ アルゴリズムや、ハッシュ テーブルのようなデータ構造での使用適してます。 (Object から継承されます。)
パブリック メソッド GetLifetimeService  対象インスタンス有効期間ポリシー制御する現在の有効期間サービス オブジェクト取得します。 (MarshalByRefObject から継承されます。)
パブリック メソッド GetType  現在のインスタンスType取得します。 (Object から継承されます。)
パブリック メソッド InitializeLifetimeService  対象インスタンス有効期間ポリシー制御する有効期間サービス オブジェクト取得します。 (MarshalByRefObject から継承されます。)
パブリック メソッド OpenExisting オーバーロードされます既存の名前付同期イベント開きます
パブリック メソッド ReferenceEquals  指定した複数Object インスタンス同一かどうか判断します。 (Object から継承されます。)
パブリック メソッド Reset イベントの状態を非シグナル状態に設定しスレッドブロックします
パブリック メソッド Set イベントの状態をシグナル状態に設定し待機している 1 つ上のスレッド進行できるようにします。
パブリック メソッド SetAccessControl 前付システム イベントアクセス制御セキュリティ設定します
パブリック メソッド SignalAndWait  オーバーロードされます分割不可能な操作として1 つWaitHandle通知し別の WaitHandle待機します。 (WaitHandle から継承されます。)
パブリック メソッド ToString  現在の Object を表す String返します。 (Object から継承されます。)
パブリック メソッド WaitAll  オーバーロードされます指定した配列内のすべての要素シグナル受信するまで待機します。 (WaitHandle から継承されます。)
パブリック メソッド WaitAny  オーバーロードされます指定した配列内のいずれか要素シグナル受信するまで待機します。 (WaitHandle から継承されます。)
パブリック メソッド WaitOne  オーバーロードされます派生クラスオーバーライドされると、現在の WaitHandleシグナル受信するまで現在のスレッドブロックします。 (WaitHandle から継承されます。)
プロテクト メソッドプロテクト メソッド
参照参照

関連項目

EventWaitHandle クラス
System.Threading 名前空間
WaitHandle
AutoResetEvent クラス
ManualResetEvent

その他の技術情報

マネージ スレッド処理
EventWaitHandle、AutoResetEvent、および ManualResetEvent



英和和英テキスト翻訳>> Weblio翻訳
英語⇒日本語日本語⇒英語
  

辞書ショートカット

すべての辞書の索引

「EventWaitHandle」の関連用語

EventWaitHandleのお隣キーワード
検索ランキング

   

英語⇒日本語
日本語⇒英語
   



EventWaitHandleのページの著作権
Weblio 辞書 情報提供元は 参加元一覧 にて確認できます。

   
日本マイクロソフト株式会社日本マイクロソフト株式会社
© 2025 Microsoft.All rights reserved.

©2025 GRAS Group, Inc.RSS