AutoResetEvent AutoResetEvent AutoResetEvent AutoResetEvent Class

定义

表示线程同步事件在一个等待线程释放后收到信号时自动重置。Represents a thread synchronization event that, when signaled, resets automatically after releasing a single waiting thread. 此类不能被继承。This class cannot be inherited.

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

示例

下面的示例演示如何使用AutoResetEvent通过调用一次释放一个线程Set方法 (基类) 每次用户需按Enter密钥。The following example shows how to use AutoResetEvent to release one thread at a time, by calling the Set method (on the base class) each time the user presses the Enter key. 该示例启动三个线程,等待AutoResetEvent中已发出信号状态的已创建。The example starts three threads, which wait on an AutoResetEvent that was created in the signaled state. 第一个线程,所以立即释放因为AutoResetEvent已处于已发出信号状态。The first thread is released immediately, because the AutoResetEvent is already in the signaled state. 这将重置AutoResetEvent为非终止状态,以便后续线程阻塞。This resets the AutoResetEvent to the non-signaled state, so that subsequent threads block. 不释放被阻止的线程,直到用户释放它们其中一个按一次Enter密钥。The blocked threads are not released until the user releases them one at a time by pressing the Enter key.

从第一个线程释放后AutoResetEvent,等待另一个AutoResetEvent中非终止状态的已创建。After the threads are released from the first AutoResetEvent, they wait on another AutoResetEvent that was created in the non-signaled state. 所有三个线程阻止,因此Set方法必须调用三次以将其释放。All three threads block, so the Set method must be called three times to release them all.

using namespace System;
using namespace System::Threading;

ref class Example
{
private:
    static AutoResetEvent^ event_1 = gcnew AutoResetEvent(true);
    static AutoResetEvent^ event_2 = gcnew AutoResetEvent(false);

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

        Console::WriteLine("{0} waits on AutoResetEvent #1.", name);
        event_1->WaitOne();
        Console::WriteLine("{0} is released from AutoResetEvent #1.", name);

        Console::WriteLine("{0} waits on AutoResetEvent #2.", name);
        event_2->WaitOne();
        Console::WriteLine("{0} is released from AutoResetEvent #2.", name);

        Console::WriteLine("{0} ends.", name);
    }

public:
    static void Demo()
    {
        Console::WriteLine("Press Enter to create three threads and start them.\r\n" +
                           "The threads wait on AutoResetEvent #1, which was created\r\n" +
                           "in the signaled state, so the first thread is released.\r\n" +
                           "This puts AutoResetEvent #1 into the unsignaled state.");
        Console::ReadLine();
            
        for (int i = 1; i < 4; i++)
        {
            Thread^ t = gcnew Thread(gcnew ThreadStart(&ThreadProc));
            t->Name = "Thread_" + i;
            t->Start();
        }
        Thread::Sleep(250);

        for (int i = 0; i < 2; i++)
        {
            Console::WriteLine("Press Enter to release another thread.");
            Console::ReadLine();
            event_1->Set();
            Thread::Sleep(250);
        }

        Console::WriteLine("\r\nAll threads are now waiting on AutoResetEvent #2.");
        for (int i = 0; i < 3; i++)
        {
            Console::WriteLine("Press Enter to release a thread.");
            Console::ReadLine();
            event_2->Set();
            Thread::Sleep(250);
        }

        // Visual Studio: Uncomment the following line.
        //Console::Readline();
    }
};

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

/* This example produces output similar to the following:

Press Enter to create three threads and start them.
The threads wait on AutoResetEvent #1, which was created
in the signaled state, so the first thread is released.
This puts AutoResetEvent #1 into the unsignaled state.

Thread_1 waits on AutoResetEvent #1.
Thread_1 is released from AutoResetEvent #1.
Thread_1 waits on AutoResetEvent #2.
Thread_3 waits on AutoResetEvent #1.
Thread_2 waits on AutoResetEvent #1.
Press Enter to release another thread.

Thread_3 is released from AutoResetEvent #1.
Thread_3 waits on AutoResetEvent #2.
Press Enter to release another thread.

Thread_2 is released from AutoResetEvent #1.
Thread_2 waits on AutoResetEvent #2.

All threads are now waiting on AutoResetEvent #2.
Press Enter to release a thread.

Thread_2 is released from AutoResetEvent #2.
Thread_2 ends.
Press Enter to release a thread.

Thread_1 is released from AutoResetEvent #2.
Thread_1 ends.
Press Enter to release a thread.

Thread_3 is released from AutoResetEvent #2.
Thread_3 ends.
 */
using System;
using System.Threading;

// Visual Studio: Replace the default class in a Console project with 
//                the following class.
class Example
{
    private static AutoResetEvent event_1 = new AutoResetEvent(true);
    private static AutoResetEvent event_2 = new AutoResetEvent(false);

    static void Main()
    {
        Console.WriteLine("Press Enter to create three threads and start them.\r\n" +
                          "The threads wait on AutoResetEvent #1, which was created\r\n" +
                          "in the signaled state, so the first thread is released.\r\n" +
                          "This puts AutoResetEvent #1 into the unsignaled state.");
        Console.ReadLine();
            
        for (int i = 1; i < 4; i++)
        {
            Thread t = new Thread(ThreadProc);
            t.Name = "Thread_" + i;
            t.Start();
        }
        Thread.Sleep(250);

        for (int i = 0; i < 2; i++)
        {
            Console.WriteLine("Press Enter to release another thread.");
            Console.ReadLine();
            event_1.Set();
            Thread.Sleep(250);
        }

        Console.WriteLine("\r\nAll threads are now waiting on AutoResetEvent #2.");
        for (int i = 0; i < 3; i++)
        {
            Console.WriteLine("Press Enter to release a thread.");
            Console.ReadLine();
            event_2.Set();
            Thread.Sleep(250);
        }

        // Visual Studio: Uncomment the following line.
        //Console.Readline();
    }

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

        Console.WriteLine("{0} waits on AutoResetEvent #1.", name);
        event_1.WaitOne();
        Console.WriteLine("{0} is released from AutoResetEvent #1.", name);

        Console.WriteLine("{0} waits on AutoResetEvent #2.", name);
        event_2.WaitOne();
        Console.WriteLine("{0} is released from AutoResetEvent #2.", name);

        Console.WriteLine("{0} ends.", name);
    }
}

/* This example produces output similar to the following:

Press Enter to create three threads and start them.
The threads wait on AutoResetEvent #1, which was created
in the signaled state, so the first thread is released.
This puts AutoResetEvent #1 into the unsignaled state.

Thread_1 waits on AutoResetEvent #1.
Thread_1 is released from AutoResetEvent #1.
Thread_1 waits on AutoResetEvent #2.
Thread_3 waits on AutoResetEvent #1.
Thread_2 waits on AutoResetEvent #1.
Press Enter to release another thread.

Thread_3 is released from AutoResetEvent #1.
Thread_3 waits on AutoResetEvent #2.
Press Enter to release another thread.

Thread_2 is released from AutoResetEvent #1.
Thread_2 waits on AutoResetEvent #2.

All threads are now waiting on AutoResetEvent #2.
Press Enter to release a thread.

Thread_2 is released from AutoResetEvent #2.
Thread_2 ends.
Press Enter to release a thread.

Thread_1 is released from AutoResetEvent #2.
Thread_1 ends.
Press Enter to release a thread.

Thread_3 is released from AutoResetEvent #2.
Thread_3 ends.
 */
Imports System.Threading

' Visual Studio: Replace the default class in a Console project with 
'                the following class.
Class Example

    Private Shared event_1 As New AutoResetEvent(True)
    Private Shared event_2 As New AutoResetEvent(False)

    <MTAThread()> _
    Shared Sub Main()
    
        Console.WriteLine("Press Enter to create three threads and start them." & vbCrLf & _
                          "The threads wait on AutoResetEvent #1, which was created" & vbCrLf & _
                          "in the signaled state, so the first thread is released." & vbCrLf & _
                          "This puts AutoResetEvent #1 into the unsignaled state.")
        Console.ReadLine()
            
        For i As Integer = 1 To 3
            Dim t As New Thread(AddressOf ThreadProc)
            t.Name = "Thread_" & i
            t.Start()
        Next
        Thread.Sleep(250)

        For i As Integer = 1 To 2
            Console.WriteLine("Press Enter to release another thread.")
            Console.ReadLine()

            event_1.Set()
            Thread.Sleep(250)
        Next

        Console.WriteLine(vbCrLf & "All threads are now waiting on AutoResetEvent #2.")
        For i As Integer = 1 To 3
            Console.WriteLine("Press Enter to release a thread.")
            Console.ReadLine()

            event_2.Set()
            Thread.Sleep(250)
        Next

        ' Visual Studio: Uncomment the following line.
        'Console.Readline()
    End Sub

    Shared Sub ThreadProc()
    
        Dim name As String = Thread.CurrentThread.Name

        Console.WriteLine("{0} waits on AutoResetEvent #1.", name)
        event_1.WaitOne()
        Console.WriteLine("{0} is released from AutoResetEvent #1.", name)

        Console.WriteLine("{0} waits on AutoResetEvent #2.", name)
        event_2.WaitOne()
        Console.WriteLine("{0} is released from AutoResetEvent #2.", name)

        Console.WriteLine("{0} ends.", name)
    End Sub
End Class

' This example produces output similar to the following:
'
'Press Enter to create three threads and start them.
'The threads wait on AutoResetEvent #1, which was created
'in the signaled state, so the first thread is released.
'This puts AutoResetEvent #1 into the unsignaled state.
'
'Thread_1 waits on AutoResetEvent #1.
'Thread_1 is released from AutoResetEvent #1.
'Thread_1 waits on AutoResetEvent #2.
'Thread_3 waits on AutoResetEvent #1.
'Thread_2 waits on AutoResetEvent #1.
'Press Enter to release another thread.
'
'Thread_3 is released from AutoResetEvent #1.
'Thread_3 waits on AutoResetEvent #2.
'Press Enter to release another thread.
'
'Thread_2 is released from AutoResetEvent #1.
'Thread_2 waits on AutoResetEvent #2.
'
'All threads are now waiting on AutoResetEvent #2.
'Press Enter to release a thread.
'
'Thread_2 is released from AutoResetEvent #2.
'Thread_2 ends.
'Press Enter to release a thread.
'
'Thread_1 is released from AutoResetEvent #2.
'Thread_1 ends.
'Press Enter to release a thread.
'
'Thread_3 is released from AutoResetEvent #2.
'Thread_3 ends.

注解

您使用AutoResetEventManualResetEvent,和EventWaitHandle线程交互 (或线程发出信号)。You use AutoResetEvent, ManualResetEvent, 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.

重要

此类型实现IDisposable接口。This type implements the IDisposable interface. 在使用完类型后,您应直接或间接释放类型。When you have finished using the type, you should dispose of it either directly or indirectly. 若要直接释放类型,调用其Dispose中的方法try / catch块。To dispose of the type directly, call its Dispose method in a try/catch block. 若要间接释放类型,请使用 using(在 C# 中)或 Using(在 Visual Basic 中)等语言构造。To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). 有关详细信息,请参阅中的"使用对象实现 IDisposable"一节IDisposable接口主题。For more information, see the "Using an Object that Implements IDisposable" section in the IDisposable interface topic.

线程通过调用等待一个信号AutoResetEvent.WaitOneA thread waits for a signal by calling AutoResetEvent.WaitOne. 如果AutoResetEvent处于非信号状态,线程阻止,直到AutoResetEvent.Set调用。If the AutoResetEvent is in the non-signaled state, the thread blocks until AutoResetEvent.Set is called.

调用Set信号AutoResetEvent释放等待线程。Calling Set signals AutoResetEvent to release a waiting thread. AutoResetEvent 将保持终止状态直到一个等待线程释放,并自动返回到非信号状态。AutoResetEvent remains signaled until a single waiting thread is released, and then automatically returns to the non-signaled state. 如果没有线程处于等待状态,状态将无限期地保持已发出信号。If no threads are waiting, the state remains signaled indefinitely.

如果某个线程调用WaitOne虽然AutoResetEvent是在已发出信号状态下,该线程不会阻止。If a thread calls WaitOne while the AutoResetEvent is in the signaled state, the thread does not block. AutoResetEvent立即释放相应线程并返回到非信号状态。The AutoResetEvent releases the thread immediately and returns to the non-signaled state.

重要

不能保证的每个调用Set方法将释放一个线程。There is no guarantee that every call to the Set method will release a thread. 如果两次调用太靠近在一起,以便第二次调用前释放线程发生,只有一个线程被释放。If two calls are too close together, so that the second call occurs before a thread has been released, only one thread is released. 就像第二次调用未发生。It's as if the second call did not happen. 此外,如果Set时没有等待的线程调用和AutoResetEvent已终止,则调用不起作用。Also, if Set is called when there are no threads waiting and the AutoResetEvent is already signaled, the call has no effect.

您可以控制的初始状态AutoResetEvent通过将一个布尔值传递给构造函数:true如果信号的初始状态和false否则为。You can control the initial state of an AutoResetEvent by passing a Boolean value to the constructor: true if the initial state is signaled and false otherwise.

AutoResetEvent 也可以用于staticWaitAllWaitAny方法。AutoResetEvent can also be used with the static WaitAll and WaitAny methods.

从.NET Framework 2.0 版中,开始AutoResetEvent派生自新EventWaitHandle类。Beginning with the .NET Framework version 2.0, AutoResetEvent derives from the new EventWaitHandle class. AutoResetEvent功能上等效于EventWaitHandle使用创建EventResetMode.AutoResetAn AutoResetEvent is functionally equivalent to an EventWaitHandle created with EventResetMode.AutoReset.

备注

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

构造函数

AutoResetEvent(Boolean) AutoResetEvent(Boolean) AutoResetEvent(Boolean) AutoResetEvent(Boolean)

用一个指示是否将初始状态设置为终止的布尔值初始化 AutoResetEvent 类的新实例。Initializes a new instance of the AutoResetEvent 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 at most one waiting thread 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.

另请参阅