Skip to main content
.NET Framework Class Library
WaitHandle Class

Encapsulates operating system–specific objects that wait for exclusive access to shared resources.

Namespace:   System.Threading
Assembly:  mscorlib (in mscorlib.dll)
Syntax
<[%$TOPIC/9f7e54k1_en-us_VS_110_2_0_0_0_0%](True)> _
Public MustInherit Class WaitHandle _
	Inherits [%$TOPIC/9f7e54k1_en-us_VS_110_2_0_0_0_1%] _
	Implements [%$TOPIC/9f7e54k1_en-us_VS_110_2_0_0_0_2%]
[[%$TOPIC/9f7e54k1_en-us_VS_110_2_0_1_0_0%](true)]
public abstract class WaitHandle : [%$TOPIC/9f7e54k1_en-us_VS_110_2_0_1_0_1%], 
	[%$TOPIC/9f7e54k1_en-us_VS_110_2_0_1_0_2%]
[[%$TOPIC/9f7e54k1_en-us_VS_110_2_0_2_0_0%](true)]
public ref class WaitHandle abstract : public [%$TOPIC/9f7e54k1_en-us_VS_110_2_0_2_0_1%], 
	[%$TOPIC/9f7e54k1_en-us_VS_110_2_0_2_0_2%]
[<[%$TOPIC/9f7e54k1_en-us_VS_110_2_0_3_0_0%]>]
[<[%$TOPIC/9f7e54k1_en-us_VS_110_2_0_3_0_1%](true)>]
type WaitHandle =  
    class 
        inherit [%$TOPIC/9f7e54k1_en-us_VS_110_2_0_3_0_2%] 
        interface [%$TOPIC/9f7e54k1_en-us_VS_110_2_0_3_0_3%] 
    end

The WaitHandle type exposes the following members.

Constructors
  NameDescription
Protected method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps WaitHandleInitializes a new instance of the WaitHandle class.
Top
Properties
  NameDescription
Public property Supported by the XNA Framework HandleObsolete. Gets or sets the native operating system handle.
Public property SafeWaitHandleGets or sets the native operating system handle.
Top
Methods
  NameDescription
Public method Supported by the XNA Framework CloseWhen overridden in a derived class, releases all resources held by the current WaitHandle.
Public method CreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public method Supported by Portable Class Library Supported in .NET for Windows Store apps DisposeReleases all resources used by the current instance of the WaitHandle class.
Protected method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Dispose(Boolean)When overridden in a derived class, releases the unmanaged resources used by the WaitHandle, and optionally releases the managed resources.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps Equals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps FinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps GetHashCodeServes as a hash function for a particular type. (Inherited from Object.)
Public method GetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps GetTypeGets the Type of the current instance. (Inherited from Object.)
Public method InitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps MemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected method MemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Public method Static member SignalAndWait(WaitHandle, WaitHandle)Signals one WaitHandle and waits on another.
Public method Static member SignalAndWait(WaitHandle, WaitHandle, Int32, Boolean)Signals one WaitHandle and waits on another, specifying a time-out interval as a 32-bit signed integer and specifying whether to exit the synchronization domain for the context before entering the wait.
Public method Static member SignalAndWait(WaitHandle, WaitHandle, TimeSpan, Boolean)Signals one WaitHandle and waits on another, specifying the time-out interval as a TimeSpan and specifying whether to exit the synchronization domain for the context before entering the wait.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps ToStringReturns a string that represents the current object. (Inherited from Object.)
Public method Static member Supported by Portable Class Library Supported in .NET for Windows Store apps WaitAll(WaitHandle)Waits for all the elements in the specified array to receive a signal.
Public method Static member Supported by Portable Class Library Supported in .NET for Windows Store apps WaitAll(WaitHandle, Int32)Waits for all the elements in the specified array to receive a signal, using an Int32 value to specify the time interval.
Public method Static member Supported by Portable Class Library Supported in .NET for Windows Store apps WaitAll(WaitHandle, TimeSpan)Waits for all the elements in the specified array to receive a signal, using a TimeSpan value to specify the time interval.
Public method Static member WaitAll(WaitHandle, Int32, Boolean)Waits for all the elements in the specified array to receive a signal, using an Int32 value to specify the time interval and specifying whether to exit the synchronization domain before the wait.
Public method Static member WaitAll(WaitHandle, TimeSpan, Boolean)Waits for all the elements in the specified array to receive a signal, using a TimeSpan value to specify the time interval, and specifying whether to exit the synchronization domain before the wait.
Public method Static member Supported by Portable Class Library Supported in .NET for Windows Store apps WaitAny(WaitHandle)Waits for any of the elements in the specified array to receive a signal.
Public method Static member Supported by Portable Class Library Supported in .NET for Windows Store apps WaitAny(WaitHandle, Int32)Waits for any of the elements in the specified array to receive a signal, using a 32-bit signed integer to specify the time interval.
Public method Static member Supported by Portable Class Library Supported in .NET for Windows Store apps WaitAny(WaitHandle, TimeSpan)Waits for any of the elements in the specified array to receive a signal, using a TimeSpan to specify the time interval.
Public method Static member WaitAny(WaitHandle, Int32, Boolean)Waits for any of the elements in the specified array to receive a signal, using a 32-bit signed integer to specify the time interval, and specifying whether to exit the synchronization domain before the wait.
Public method Static member WaitAny(WaitHandle, TimeSpan, Boolean)Waits for any of the elements in the specified array to receive a signal, using a TimeSpan to specify the time interval and specifying whether to exit the synchronization domain before the wait.
Public method Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps WaitOneBlocks the current thread until the current WaitHandle receives a signal.
Public method Supported by Portable Class Library Supported in .NET for Windows Store apps WaitOne(Int32)Blocks the current thread until the current WaitHandle receives a signal, using a 32-bit signed integer to specify the time interval.
Public method Supported by Portable Class Library Supported in .NET for Windows Store apps WaitOne(TimeSpan)Blocks the current thread until the current instance receives a signal, using a TimeSpan to specify the time interval.
Public method Supported by the XNA Framework WaitOne(Int32, Boolean)Blocks the current thread until the current WaitHandle receives a signal, using a 32-bit signed integer to specify the time interval and specifying whether to exit the synchronization domain before the wait.
Public method WaitOne(TimeSpan, Boolean)Blocks the current thread until the current instance receives a signal, using a TimeSpan to specify the time interval and specifying whether to exit the synchronization domain before the wait.
Top
Fields
  NameDescription
Protected field Static member Supported by the XNA Framework Supported by Portable Class Library Supported in .NET for Windows Store apps InvalidHandleRepresents an invalid native operating system handle. This field is read-only.
Public field Static member Supported by Portable Class Library Supported in .NET for Windows Store apps WaitTimeoutIndicates that a WaitAny operation timed out before any of the wait handles were signaled. This field is constant.
Top
Explicit Interface Implementations
  NameDescription
Explicit interface implemetation Private method Supported by the XNA Framework IDisposableDisposeInfrastructure. Releases all resources used by the WaitHandle.
Top
Remarks

This class is typically used as a base class for synchronization objects. Classes derived from WaitHandle define a signaling mechanism to indicate taking or releasing access to a shared resource, but use the inherited WaitHandle methods to block while waiting for access to shared resources.

Use the static methods of this class to block a thread until one or more synchronization objects receive a signal.

WaitHandle implements the Dispose pattern. See Dispose Pattern. When you derive from WaitHandle, use the SafeWaitHandle property to store your native handle operating system handle. You do not need to override the protected Dispose method unless you use additional unmanaged resources.

Examples

The following code example shows how two threads can do background tasks while the Main thread waits for the tasks to complete using the static WaitAny and WaitAll methods of the WaitHandle class.

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).
Version Information

.NET Framework

Supported in: 4.5, 4, 3.5, 3.0, 2.0, 1.1, 1.0

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

Portable Class Library

Supported in: Portable Class Library

.NET for Windows Store apps

Supported in: Windows 8
Platforms

Windows 8, Windows Server 2012, Windows 7, Windows Vista SP2, Windows Server 2008 (Server Core Role not supported), Windows Server 2008 R2 (Server Core Role supported with SP1 or later; Itanium not supported)

The .NET Framework does not support all versions of every platform. For a list of the supported versions, see .NET Framework System Requirements.

Thread Safety

This type is thread safe.