ManualResetEvent ManualResetEvent ManualResetEvent ManualResetEvent Class

定义

表示线程同步事件,收到信号时,必须手动重置该事件。Represents a thread synchronization event that, when signaled, must be reset manually. 此类不能被继承。This class cannot be inherited.

public ref class ManualResetEvent sealed : System::Threading::EventWaitHandle
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class ManualResetEvent : System.Threading.EventWaitHandle
type ManualResetEvent = class
    inherit EventWaitHandle
Public NotInheritable Class ManualResetEvent
Inherits EventWaitHandle
继承
属性

示例

下面的示例演示如何ManualResetEvent工作。The following example demonstrates how ManualResetEvent works. 该示例以信号状态ManualResetEvent ( false即传递给构造函数的) 开头。The example starts with a ManualResetEvent in the unsignaled state (that is, false is passed to the constructor). 该示例创建三个线程, 每个线程ManualResetEvent通过调用其WaitOne方法, 在上被阻止。The example creates three threads, each of which blocks on the ManualResetEvent by calling its WaitOne method. 当用户按Enter键时, 该示例调用Set方法, 该方法释放所有三个线程。When the user presses the Enter key, the example calls the Set method, which releases all three threads. 将此与AutoResetEvent类的行为进行对比, 每次释放一个线程, 并在每次发布后自动重置。Contrast this with the behavior of the AutoResetEvent class, which releases threads one at a time, resetting automatically after each release.

再次按 " enter " 键, 表明ManualResetEvent在调用Reset方法之前, 将一直保持终止状态:该示例将启动两个以上的线程。Pressing the Enter key again demonstrates that the ManualResetEvent remains in the signaled state until its Reset method is called: The example starts two more threads. 这些线程在调用WaitOne方法时不会被阻止, 而是运行到完成。These threads do not block when they call the WaitOne method, but instead run to completion.

再次按enter键将导致该示例调用Reset方法, 并启动一个线程, 该线程在调用WaitOne时将被阻止。Pressing the Enter key again causes the example to call the Reset method and to start one more thread, which blocks when it calls WaitOne. enter键, 最后一次调用Set以释放最后一个线程, 程序结束。Pressing the Enter key one final time calls Set to release the last thread, and the program ends.

using namespace System;
using namespace System::Threading;

ref class Example
{
private:
    // mre is used to block and release threads manually. It is
    // created in the unsignaled state.
    static ManualResetEvent^ mre = gcnew ManualResetEvent(false);

    static void ThreadProc()
    {
        String^ name = Thread::CurrentThread->Name;

        Console::WriteLine(name + " starts and calls mre->WaitOne()");

        mre->WaitOne();

        Console::WriteLine(name + " ends.");
    }

public:
    static void Demo()
    {
        Console::WriteLine("\nStart 3 named threads that block on a ManualResetEvent:\n");

        for(int i = 0; i <=2 ; i++)
        {
            Thread^ t = gcnew Thread(gcnew ThreadStart(ThreadProc));
            t->Name = "Thread_" + i;
            t->Start();
        }

        Thread::Sleep(500);
        Console::WriteLine("\nWhen all three threads have started, press Enter to call Set()" +
                           "\nto release all the threads.\n");
        Console::ReadLine();

        mre->Set();

        Thread::Sleep(500);
        Console::WriteLine("\nWhen a ManualResetEvent is signaled, threads that call WaitOne()" +
                           "\ndo not block. Press Enter to show this.\n");
        Console::ReadLine();

        for(int i = 3; i <= 4; i++)
        {
            Thread^ t = gcnew Thread(gcnew ThreadStart(ThreadProc));
            t->Name = "Thread_" + i;
            t->Start();
        }

        Thread::Sleep(500);
        Console::WriteLine("\nPress Enter to call Reset(), so that threads once again block" +
                           "\nwhen they call WaitOne().\n");
        Console::ReadLine();

        mre->Reset();

        // Start a thread that waits on the ManualResetEvent.
        Thread^ t5 = gcnew Thread(gcnew ThreadStart(ThreadProc));
        t5->Name = "Thread_5";
        t5->Start();

        Thread::Sleep(500);
        Console::WriteLine("\nPress Enter to call Set() and conclude the demo.");
        Console::ReadLine();

        mre->Set();

        // If you run this example in Visual Studio, uncomment the following line:
        //Console::ReadLine();
    }
};

int main()
{
   Example::Demo();
}

/* This example produces output similar to the following:

Start 3 named threads that block on a ManualResetEvent:

Thread_0 starts and calls mre->WaitOne()
Thread_1 starts and calls mre->WaitOne()
Thread_2 starts and calls mre->WaitOne()

When all three threads have started, press Enter to call Set()
to release all the threads.


Thread_2 ends.
Thread_1 ends.
Thread_0 ends.

When a ManualResetEvent is signaled, threads that call WaitOne()
do not block. Press Enter to show this.


Thread_3 starts and calls mre->WaitOne()
Thread_3 ends.
Thread_4 starts and calls mre->WaitOne()
Thread_4 ends.

Press Enter to call Reset(), so that threads once again block
when they call WaitOne().


Thread_5 starts and calls mre->WaitOne()

Press Enter to call Set() and conclude the demo.

Thread_5 ends.
 */
using System;
using System.Threading;

public class Example
{
    // mre is used to block and release threads manually. It is
    // created in the unsignaled state.
    private static ManualResetEvent mre = new ManualResetEvent(false);

    static void Main()
    {
        Console.WriteLine("\nStart 3 named threads that block on a ManualResetEvent:\n");

        for(int i = 0; i <= 2; i++)
        {
            Thread t = new Thread(ThreadProc);
            t.Name = "Thread_" + i;
            t.Start();
        }

        Thread.Sleep(500);
        Console.WriteLine("\nWhen all three threads have started, press Enter to call Set()" +
                          "\nto release all the threads.\n");
        Console.ReadLine();

        mre.Set();

        Thread.Sleep(500);
        Console.WriteLine("\nWhen a ManualResetEvent is signaled, threads that call WaitOne()" +
                          "\ndo not block. Press Enter to show this.\n");
        Console.ReadLine();

        for(int i = 3; i <= 4; i++)
        {
            Thread t = new Thread(ThreadProc);
            t.Name = "Thread_" + i;
            t.Start();
        }

        Thread.Sleep(500);
        Console.WriteLine("\nPress Enter to call Reset(), so that threads once again block" +
                          "\nwhen they call WaitOne().\n");
        Console.ReadLine();

        mre.Reset();

        // Start a thread that waits on the ManualResetEvent.
        Thread t5 = new Thread(ThreadProc);
        t5.Name = "Thread_5";
        t5.Start();

        Thread.Sleep(500);
        Console.WriteLine("\nPress Enter to call Set() and conclude the demo.");
        Console.ReadLine();

        mre.Set();

        // If you run this example in Visual Studio, uncomment the following line:
        //Console.ReadLine();
    }


    private static void ThreadProc()
    {
        string name = Thread.CurrentThread.Name;

        Console.WriteLine(name + " starts and calls mre.WaitOne()");

        mre.WaitOne();

        Console.WriteLine(name + " ends.");
    }
}

/* This example produces output similar to the following:

Start 3 named threads that block on a ManualResetEvent:

Thread_0 starts and calls mre.WaitOne()
Thread_1 starts and calls mre.WaitOne()
Thread_2 starts and calls mre.WaitOne()

When all three threads have started, press Enter to call Set()
to release all the threads.


Thread_2 ends.
Thread_0 ends.
Thread_1 ends.

When a ManualResetEvent is signaled, threads that call WaitOne()
do not block. Press Enter to show this.


Thread_3 starts and calls mre.WaitOne()
Thread_3 ends.
Thread_4 starts and calls mre.WaitOne()
Thread_4 ends.

Press Enter to call Reset(), so that threads once again block
when they call WaitOne().


Thread_5 starts and calls mre.WaitOne()

Press Enter to call Set() and conclude the demo.

Thread_5 ends.
 */
Imports System.Threading

Public Class Example

    ' mre is used to block and release threads manually. It is
    ' created in the unsignaled state.
    Private Shared mre As New ManualResetEvent(False)

    <MTAThreadAttribute> _
    Shared Sub Main()

        Console.WriteLine(vbLf & _
            "Start 3 named threads that block on a ManualResetEvent:" & vbLf)

        For i As Integer = 0 To 2
            Dim t As New Thread(AddressOf ThreadProc)
            t.Name = "Thread_" & i
            t.Start()
        Next i

        Thread.Sleep(500)
        Console.WriteLine(vbLf & _
            "When all three threads have started, press Enter to call Set()" & vbLf & _
            "to release all the threads." & vbLf)
        Console.ReadLine()

        mre.Set()

        Thread.Sleep(500)
        Console.WriteLine(vbLf & _
            "When a ManualResetEvent is signaled, threads that call WaitOne()" & vbLf & _
            "do not block. Press Enter to show this." & vbLf)
        Console.ReadLine()

        For i As Integer = 3 To 4
            Dim t As New Thread(AddressOf ThreadProc)
            t.Name = "Thread_" & i
            t.Start()
        Next i

        Thread.Sleep(500)
        Console.WriteLine(vbLf & _
            "Press Enter to call Reset(), so that threads once again block" & vbLf & _
            "when they call WaitOne()." & vbLf)
        Console.ReadLine()

        mre.Reset()

        ' Start a thread that waits on the ManualResetEvent.
        Dim t5 As New Thread(AddressOf ThreadProc)
        t5.Name = "Thread_5"
        t5.Start()

        Thread.Sleep(500)
        Console.WriteLine(vbLf & "Press Enter to call Set() and conclude the demo.")
        Console.ReadLine()

        mre.Set()

        ' If you run this example in Visual Studio, uncomment the following line:
        'Console.ReadLine()

    End Sub


    Private Shared Sub ThreadProc()

        Dim name As String = Thread.CurrentThread.Name

        Console.WriteLine(name & " starts and calls mre.WaitOne()")

        mre.WaitOne()

        Console.WriteLine(name & " ends.")

    End Sub

End Class

' This example produces output similar to the following:
'
'Start 3 named threads that block on a ManualResetEvent:
'
'Thread_0 starts and calls mre.WaitOne()
'Thread_1 starts and calls mre.WaitOne()
'Thread_2 starts and calls mre.WaitOne()
'
'When all three threads have started, press Enter to call Set()
'to release all the threads.
'
'
'Thread_2 ends.
'Thread_0 ends.
'Thread_1 ends.
'
'When a ManualResetEvent is signaled, threads that call WaitOne()
'do not block. Press Enter to show this.
'
'
'Thread_3 starts and calls mre.WaitOne()
'Thread_3 ends.
'Thread_4 starts and calls mre.WaitOne()
'Thread_4 ends.
'
'Press Enter to call Reset(), so that threads once again block
'when they call WaitOne().
'
'
'Thread_5 starts and calls mre.WaitOne()
'
'Press Enter to call Set() and conclude the demo.
'
'Thread_5 ends.

注解

使用ManualResetEventAutoResetEvent和进行线程交互(或线程信号)。EventWaitHandleYou use ManualResetEvent, AutoResetEvent, and EventWaitHandle for thread interaction (or thread signaling). 有关详细信息, 请参阅同步基元概述一文中的 "线程交互" 或 "信号" 部分。For more information, see the Thread interaction, or signaling section of the Overview of synchronization primitives article.

当线程开始在其他线程继续之前必须完成的活动时, 它将调用ManualResetEvent以置于ManualResetEvent非终止状态。When a thread begins an activity that must complete before other threads proceed, it calls ManualResetEvent.Reset to put ManualResetEvent in the non-signaled state. 此线程可以被视为控制ManualResetEventThis thread can be thought of as controlling the ManualResetEvent. 调用ManualResetEvent WaitOne的线程, 等待信号。Threads that call ManualResetEvent.WaitOne block, awaiting the signal. 控制线程完成活动后, 它将调用ManualResetEvent , 以指示等待线程可以继续。When the controlling thread completes the activity, it calls ManualResetEvent.Set to signal that the waiting threads can proceed. 所有等待线程都已释放。All waiting threads are released.

收到信号后, 将保持ManualResetEvent信号, 直到通过Reset()调用方法手动重置。Once it has been signaled, ManualResetEvent remains signaled until it is manually reset by calling the Reset() method. 也就是说, 调用WaitOne会立即返回。That is, calls to WaitOne return immediately.

可以通过将布尔值传递到构造ManualResetEvent函数来控制的初始状态: true如果初始false状态为 "已终止", 则为; 否则为。You can control the initial state of a ManualResetEvent by passing a Boolean value to the constructor: true if the initial state is signaled, and false otherwise.

ManualResetEvent还可与static WaitAllWaitAny方法一起使用。ManualResetEvent can also be used with the static WaitAll and WaitAny methods.

从 .NET Framework 版本2.0 开始, ManualResetEvent派生自类。EventWaitHandleBeginning with the .NET Framework version 2.0, ManualResetEvent derives from the EventWaitHandle class. ManualResetEvent功能上等效EventWaitHandle于使用EventResetMode.ManualReset创建的。A ManualResetEvent is functionally equivalent to an EventWaitHandle created with EventResetMode.ManualReset.

备注

与类不同, 类EventWaitHandle提供对已命名的系统同步事件的访问。 ManualResetEventUnlike the ManualResetEvent class, the EventWaitHandle class provides access to named system synchronization events.

从 .NET Framework 版本4.0 开始, System.Threading.ManualResetEventSlim类是的轻型ManualResetEvent替代项。Beginning with the .NET Framework version 4.0, the System.Threading.ManualResetEventSlim class is a lightweight alternative to ManualResetEvent.

构造函数

ManualResetEvent(Boolean) ManualResetEvent(Boolean) ManualResetEvent(Boolean) ManualResetEvent(Boolean)

用一个指示是否将初始状态设置为终止的布尔值初始化 ManualResetEvent 类的新实例。Initializes a new instance of the ManualResetEvent class with a Boolean value indicating whether to set the initial state to signaled.

方法

Close() Close() Close() Close()

释放由当前 WaitHandle 占用的所有资源。Releases all resources held by the current WaitHandle.

(Inherited from WaitHandle)
CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) 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() Dispose() Dispose() Dispose()

释放 WaitHandle 类的当前实例所使用的所有资源。Releases all resources used by the current instance of the WaitHandle class.

(Inherited from WaitHandle)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

当在派生类中重写时,释放 WaitHandle 使用的非托管资源,并且可选择释放托管资源。When overridden in a derived class, releases the unmanaged resources used by the WaitHandle, and optionally releases the managed resources.

(Inherited from WaitHandle)
Equals(Object) Equals(Object) Equals(Object) Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(Inherited from Object)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

作为默认哈希函数。Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetType() GetType() GetType() GetType()

获取当前实例的 TypeGets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
Reset() Reset() Reset() Reset()

将事件状态设置为非终止,从而导致线程受阻。Sets the state of the event to nonsignaled, which causes threads to block.

Set() Set() Set() Set()

将事件状态设置为终止状态,从而允许继续执行一个或多个等待线程。Sets the state of the event to signaled, which allows one or more waiting threads to proceed.

ToString() ToString() ToString() ToString()

返回表示当前对象的字符串。Returns a string that represents the current object.

(Inherited from Object)
WaitOne() WaitOne() WaitOne() WaitOne()

阻止当前线程,直到当前 WaitHandle 收到信号。Blocks the current thread until the current WaitHandle receives a signal.

(Inherited from WaitHandle)
WaitOne(Int32) WaitOne(Int32) WaitOne(Int32) WaitOne(Int32)

阻止当前线程,直到当前 WaitHandle 收到信号,同时使用 32 位带符号整数指定时间间隔(以毫秒为单位)。Blocks the current thread until the current WaitHandle receives a signal, using a 32-bit signed integer to specify the time interval in milliseconds.

(Inherited from WaitHandle)
WaitOne(Int32, Boolean) WaitOne(Int32, Boolean) WaitOne(Int32, Boolean) WaitOne(Int32, Boolean)

阻止当前线程,直到当前的 WaitHandle 收到信号为止,同时使用 32 位带符号整数指定时间间隔,并指定是否在等待之前退出同步域。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.

(Inherited from WaitHandle)
WaitOne(TimeSpan) WaitOne(TimeSpan) WaitOne(TimeSpan) WaitOne(TimeSpan)

阻止当前线程,直到当前实例收到信号,同时使用 TimeSpan 指定时间间隔。Blocks the current thread until the current instance receives a signal, using a TimeSpan to specify the time interval.

(Inherited from WaitHandle)
WaitOne(TimeSpan, Boolean) WaitOne(TimeSpan, Boolean) WaitOne(TimeSpan, Boolean) WaitOne(TimeSpan, Boolean)

阻止当前线程,直到当前实例收到信号为止,同时使用 TimeSpan 指定时间间隔,并指定是否在等待之前退出同步域。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.

(Inherited from WaitHandle)

属性

Handle Handle Handle Handle

获取或设置本机操作系统句柄。Gets or sets the native operating system handle.

(Inherited from WaitHandle)
SafeWaitHandle SafeWaitHandle SafeWaitHandle SafeWaitHandle

获取或设置本机操作系统句柄。Gets or sets the native operating system handle.

(Inherited from WaitHandle)

显式界面实现

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose()

释放由 WaitHandle 使用的所有资源。Releases all resources used by the WaitHandle.

(Inherited from WaitHandle)

字段

WaitTimeout WaitTimeout WaitTimeout WaitTimeout

指示在任何等待句柄终止之前 WaitAny(WaitHandle[], Int32, Boolean) 操作已超时。Indicates that a WaitAny(WaitHandle[], Int32, Boolean) operation timed out before any of the wait handles were signaled. 此字段为常数。This field is constant.

(Inherited from WaitHandle)

扩展方法

GetSafeWaitHandle(WaitHandle) GetSafeWaitHandle(WaitHandle) GetSafeWaitHandle(WaitHandle) GetSafeWaitHandle(WaitHandle)

获取本机操作系统等待句柄的安全句柄。Gets the safe handle for a native operating system wait handle.

SetSafeWaitHandle(WaitHandle, SafeWaitHandle) SetSafeWaitHandle(WaitHandle, SafeWaitHandle) SetSafeWaitHandle(WaitHandle, SafeWaitHandle) SetSafeWaitHandle(WaitHandle, SafeWaitHandle)

设置本机操作系统等待句柄的安全句柄。Sets a safe handle for a native operating system wait handle.

适用于

线程安全性

此类是线程安全的。This class is thread safe.

另请参阅