Επεξεργασία

Κοινή χρήση μέσω


WaitHandle Class

Definition

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

public ref class WaitHandle abstract : IDisposable
public ref class WaitHandle abstract : MarshalByRefObject, IDisposable
public abstract class WaitHandle : IDisposable
public abstract class WaitHandle : MarshalByRefObject, IDisposable
[System.Runtime.InteropServices.ComVisible(true)]
public abstract class WaitHandle : MarshalByRefObject, IDisposable
type WaitHandle = class
    interface IDisposable
type WaitHandle = class
    inherit MarshalByRefObject
    interface IDisposable
[<System.Runtime.InteropServices.ComVisible(true)>]
type WaitHandle = class
    inherit MarshalByRefObject
    interface IDisposable
Public MustInherit Class WaitHandle
Implements IDisposable
Public MustInherit Class WaitHandle
Inherits MarshalByRefObject
Implements IDisposable
Inheritance
WaitHandle
Inheritance
Derived
Attributes
Implements

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.

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).
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 task is 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).
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
    
    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
End Class

' 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).

Remarks

The WaitHandle class encapsulates a native operating system synchronization handle and is used to represent all synchronization objects in the runtime that allow multiple wait operations. For a comparison of wait handles with other synchronization objects, see Overview of Synchronization Primitives.

The WaitHandle class itself is abstract. Classes derived from WaitHandle define a signaling mechanism to indicate taking or releasing access to a shared resource, but they use the inherited WaitHandle methods to block while waiting for access to shared resources. The classes derived from WaitHandle include:

Threads can block on an individual wait handle by calling the instance method WaitOne, which is inherited by classes derived from WaitHandle.

The derived classes of WaitHandle differ in their thread affinity. Event wait handles (EventWaitHandle, AutoResetEvent, and ManualResetEvent) and semaphores do not have thread affinity; any thread can signal an event wait handle or semaphore. Mutexes, on the other hand, do have thread affinity; the thread that owns a mutex must release it, and an exception is thrown if a thread calls the ReleaseMutex method on a mutex that it does not own.

Because the WaitHandle class derives from MarshalByRefObject, these classes can be used to synchronize the activities of threads across application domain boundaries.

In addition to its derived classes, the WaitHandle class has a number of static methods that block a thread until one or more synchronization objects receive a signal. These include:

  • SignalAndWait, which allows a thread to signal one wait handle and immediately wait on another.

  • WaitAll, which allows a thread to wait until all the wait handles in an array receive a signal.

  • WaitAny, which allows a thread to wait until any one of a specified set of wait handles has been signaled.

The overloads of these methods provide timeout intervals for abandoning the wait, and the opportunity to exit a synchronization context before entering the wait, allowing other threads to use the synchronization context.

Important

This type implements the IDisposable interface. When you have finished using the type or a type derived from it, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Close method in a try/catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

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

Constructors

WaitHandle()

Initializes a new instance of the WaitHandle class.

Fields

InvalidHandle

Represents an invalid native operating system handle. This field is read-only.

WaitTimeout

Indicates that a WaitAny(WaitHandle[], Int32, Boolean) operation timed out before any of the wait handles were signaled. This field is constant.

Properties

Handle
Obsolete.
Obsolete.

Gets or sets the native operating system handle.

SafeWaitHandle

Gets or sets the native operating system handle.

Methods

Close()

Releases all resources held by the current WaitHandle.

CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose()

Releases all resources used by the current instance of the WaitHandle class.

Dispose(Boolean)

When overridden in a derived class, releases the unmanaged resources used by the WaitHandle, and optionally releases the managed resources.

Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
Finalize()

Releases the resources held by the current instance.

GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLifetimeService()
Obsolete.

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetType()

Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService()
Obsolete.

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
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.

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.

SignalAndWait(WaitHandle, WaitHandle)

Signals one WaitHandle and waits on another.

ToString()

Returns a string that represents the current object.

(Inherited from Object)
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.

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.

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.

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.

WaitAll(WaitHandle[])

Waits for all the elements in the specified array to receive a signal.

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.

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.

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.

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.

WaitAny(WaitHandle[])

Waits for any of the elements in the specified array to receive a signal.

WaitOne()

Blocks the current thread until the current WaitHandle receives a signal.

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.

WaitOne(Int32)

Blocks the current thread until the current WaitHandle receives a signal, using a 32-bit signed integer to specify the time interval in milliseconds.

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.

WaitOne(TimeSpan)

Blocks the current thread until the current instance receives a signal, using a TimeSpan to specify the time interval.

Explicit Interface Implementations

IDisposable.Dispose()

This API supports the product infrastructure and is not intended to be used directly from your code.

Releases all resources used by the WaitHandle.

Extension Methods

GetSafeWaitHandle(WaitHandle)

Gets the safe handle for a native operating system wait handle.

SetSafeWaitHandle(WaitHandle, SafeWaitHandle)

Sets a safe handle for a native operating system wait handle.

Applies to

Thread Safety

This type is thread safe.

See also