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

WaitHandle クラス

共有リソースへの排他アクセスの待機に使用するオペレーティング システム固有のオブジェクトをカプセル化します。

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

<ComVisibleAttribute(True)> _
Public MustInherit Class
 WaitHandle
    Inherits MarshalByRefObject
    Implements IDisposable
[ComVisibleAttribute(true)] 
public abstract class WaitHandle : MarshalByRefObject,
 IDisposable
[ComVisibleAttribute(true)] 
public ref class WaitHandle abstract : public
 MarshalByRefObject, IDisposable
/** @attribute ComVisibleAttribute(true) */ 
public abstract class WaitHandle extends MarshalByRefObject
 implements IDisposable
ComVisibleAttribute(true) 
public abstract class WaitHandle extends
 MarshalByRefObject implements IDisposable
解説解説
使用例使用例

2 つのスレッドがバックグラウンド タスクを実行し、その間にメイン スレッドが WaitHandle クラスの WaitAny 静的メソッドおよび WaitAll 静的メソッドを使用してタスクの完了を待機できるようにするコード例を次に示します。

Imports System
Imports System.Threading

NotInheritable Public Class
 App
    ' Define an array with two AutoResetEvent WaitHandles.
    Private Shared waitHandles() As
 WaitHandle = _
        {New AutoResetEvent(False), New AutoResetEvent(False)}
    
    ' Define a random number generator for testing.
    Private Shared r As
 New Random()
    
    <MTAThreadAttribute> _
    Public Shared Sub Main()
 
        ' Queue two tasks on two different threads; 
        ' wait until all tasks are completed.
        Dim dt As DateTime = DateTime.Now
        Console.WriteLine("Main thread is waiting for BOTH tasks
 to complete.")
        ThreadPool.QueueUserWorkItem(AddressOf DoTask, waitHandles(0))
        ThreadPool.QueueUserWorkItem(AddressOf DoTask, waitHandles(1))
        WaitHandle.WaitAll(waitHandles)
        ' The time shown below should match the longest task.
        Console.WriteLine("Both tasks are completed (time waited={0})",
 _
            (DateTime.Now - dt).TotalMilliseconds)
        
        ' Queue up two tasks on two different threads; 
        ' wait until any tasks are completed.
        dt = DateTime.Now
        Console.WriteLine()
        Console.WriteLine("The main thread is waiting for either
 task to complete.")
        ThreadPool.QueueUserWorkItem(AddressOf DoTask, waitHandles(0))
        ThreadPool.QueueUserWorkItem(AddressOf DoTask, waitHandles(1))
        Dim index As Integer
 = WaitHandle.WaitAny(waitHandles)
        ' The time shown below should match the shortest task.
        Console.WriteLine("Task {0} finished first (time waited={1}).",
 _
            index + 1,(DateTime.Now - dt).TotalMilliseconds)
    
    End Sub 'Main
    
    Shared Sub DoTask(ByVal
 state As [Object]) 
        Dim are As AutoResetEvent = CType(state,
 AutoResetEvent)
        Dim time As Integer
 = 1000 * r.Next(2, 10)
        Console.WriteLine("Performing a task for {0} milliseconds.",
 time)
        Thread.Sleep(time)
        are.Set()
    
    End Sub 'DoTask
End Class 'App

' This code produces output similar to the following:
'
'  Main thread is waiting for BOTH tasks to complete.
'  Performing a task for 7000 milliseconds.
'  Performing a task for 4000 milliseconds.
'  Both tasks are completed (time waited=7064.8052)
' 
'  The main thread is waiting for either task to complete.
'  Performing a task for 2000 milliseconds.
'  Performing a task for 2000 milliseconds.
'  Task 1 finished first (time waited=2000.6528).
using System;
using System.Threading;

public sealed class App 
{
    // Define an array with two AutoResetEvent WaitHandles.
    static WaitHandle[] waitHandles = new WaitHandle[]
 
    {
        new AutoResetEvent(false),
        new AutoResetEvent(false)
    };

    // Define a random number generator for testing.
    static Random r = new Random();

    static void Main() 
    {
        // Queue up two tasks on two different threads; 
        // wait until all tasks are completed.
        DateTime dt = DateTime.Now;
        Console.WriteLine("Main thread is waiting for BOTH
 tasks to complete.");
        ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask),
 waitHandles[0]);
        ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask),
 waitHandles[1]);
        WaitHandle.WaitAll(waitHandles);
        // The time shown below should match the longest task.
        Console.WriteLine("Both tasks are completed (time waited={0})",
 
            (DateTime.Now - dt).TotalMilliseconds);

        // Queue up two tasks on two different threads; 
        // wait until any tasks are completed.
        dt = DateTime.Now;
        Console.WriteLine();
        Console.WriteLine("The main thread is waiting for
 either task to complete.");
        ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask),
 waitHandles[0]);
        ThreadPool.QueueUserWorkItem(new WaitCallback(DoTask),
 waitHandles[1]);
        int index = WaitHandle.WaitAny(waitHandles);
        // The time shown below should match the shortest task.
        Console.WriteLine("Task {0} finished first (time waited={1})."
,
            index + 1, (DateTime.Now - dt).TotalMilliseconds);
    }

    static void DoTask(Object state) 
    {
        AutoResetEvent are = (AutoResetEvent) state;
        int time = 1000 * r.Next(2, 10);
        Console.WriteLine("Performing a task for {0} milliseconds.",
 time);
        Thread.Sleep(time);
        are.Set();
    }
}

// This code produces output similar to the following:
//
//  Main thread is waiting for BOTH tasks to complete.
//  Performing a task for 7000 milliseconds.
//  Performing a task for 4000 milliseconds.
//  Both tasks are completed (time waited=7064.8052)
// 
//  The main thread is waiting for either task to complete.
//  Performing a task for 2000 milliseconds.
//  Performing a task for 2000 milliseconds.
//  Task 1 finished first (time waited=2000.6528).
using namespace System;
using namespace System::Threading;

public ref class WaitHandleExample
{
    // Define a random number generator for testing.
private:
    static Random^ random = gcnew Random();
public:
    static void DoTask(Object^ state)
    {
        AutoResetEvent^ autoReset = (AutoResetEvent^) state;
        int time = 1000 * random->Next(2, 10);
        Console::WriteLine("Performing a task for {0} milliseconds.",
 time);
        Thread::Sleep(time);
        autoReset->Set();
    }
};

int main()
{
    // Define an array with two AutoResetEvent WaitHandles.
    array<WaitHandle^>^ handles = gcnew array<WaitHandle^> {
        gcnew AutoResetEvent(false), gcnew AutoResetEvent(false)};

    // Queue up two tasks on two different threads;
    // wait until all tasks are completed.
    DateTime timeInstance = DateTime::Now;
    Console::WriteLine("Main thread is waiting for BOTH tasks
 to " +
        "complete.");
    ThreadPool::QueueUserWorkItem(
        gcnew WaitCallback(WaitHandleExample::DoTask), handles[0]);
    ThreadPool::QueueUserWorkItem(
        gcnew WaitCallback(WaitHandleExample::DoTask), handles[1]);
    WaitHandle::WaitAll(handles);
    // The time shown below should match the longest task.
    Console::WriteLine("Both tasks are completed (time waited={0})",
        (DateTime::Now - timeInstance).TotalMilliseconds);

    // Queue up two tasks on two different threads;
    // wait until any tasks are completed.
    timeInstance = DateTime::Now;
    Console::WriteLine();
    Console::WriteLine("The main thread is waiting for either
 task to " +
        "complete.");
    ThreadPool::QueueUserWorkItem(
        gcnew WaitCallback(WaitHandleExample::DoTask), handles[0]);
    ThreadPool::QueueUserWorkItem(
        gcnew WaitCallback(WaitHandleExample::DoTask), handles[1]);
    int index = WaitHandle::WaitAny(handles);
    // The time shown below should match the shortest task.
    Console::WriteLine("Task {0} finished first (time waited={1}).",
        index + 1, (DateTime::Now - timeInstance).TotalMilliseconds);
}

// This code produces the following sample output.
//
// Main thread is waiting for BOTH tasks to complete.
// Performing a task for 7000 milliseconds.
// Performing a task for 4000 milliseconds.
// Both tasks are completed (time waited=7064.8052)

// The main thread is waiting for either task to complete.
// Performing a task for 2000 milliseconds.
// Performing a task for 2000 milliseconds.
// Task 1 finished first (time waited=2000.6528).
継承階層継承階層
System.Object
   System.MarshalByRefObject
    System.Threading.WaitHandle
       System.Threading.EventWaitHandle
       System.Threading.Mutex
       System.Threading.Semaphore
スレッド セーフスレッド セーフ

この型は、スレッド セーフです。

プラットフォームプラットフォーム
バージョン情報バージョン情報
参照参照

WaitHandle コンストラクタ


WaitHandle フィールド


WaitHandle プロパティ


WaitHandle メソッド


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

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

関連項目

WaitHandle クラス
System.Threading 名前空間

その他の技術情報

待機ハンドル

WaitHandle メンバ

共有リソースへの排他アクセスの待機に使用するオペレーティング システム固有のオブジェクトをカプセル化します。

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


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

関連項目

WaitHandle クラス
System.Threading 名前空間

その他の技術情報

待機ハンドル



英和和英テキスト翻訳

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

辞書ショートカット

すべての辞書の索引

「WaitHandle」の関連用語

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

   

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



WaitHandleのページの著作権

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

©2026 GRAS Group, Inc.RSS