AutoResetEvent 类的学习网站

本文摘自:https://docs.microsoft.com/zh-cn/dotnet/api/system.threading.autoresetevent?view=netframework-4.8

AutoResetEvent 类

定义

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

本文内容

  1. 定义
  2. 示例
  3. 注解
  4. 构造函数
  5. 字段
  6. 属性
  7. 方法
  8. 显式接口实现
  9. 扩展方法
  10. 适用于
  11. 线程安全性
  12. 另请参阅
public ref class AutoResetEvent sealed : System::Threading::EventWaitHandle
public ref class AutoResetEvent sealed : System::Threading::WaitHandle
C#
public sealed class AutoResetEvent : System.Threading.EventWaitHandle
C#
public sealed class AutoResetEvent : System.Threading.WaitHandle
C#
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class AutoResetEvent : System.Threading.EventWaitHandle
type AutoResetEvent = class
    inherit EventWaitHandle
type AutoResetEvent = class
    inherit WaitHandle
Public NotInheritable Class AutoResetEvent
Inherits EventWaitHandle
Public NotInheritable Class AutoResetEvent
Inherits WaitHandle
继承
继承
继承
属性

示例

下面的示例演示了如何使用 AutoResetEvent 通过在用户按Enter键时调用 Set 方法(在基类上),一次释放一个线程。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. 该示例启动三个线程,这些线程等待在终止状态下创建的 AutoResetEventThe 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.
" +
                           "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.");
        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("
All 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.
 */
C#
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.
" +
                          "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.");
        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("
All 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.

注解

你使用 AutoResetEventManualResetEventEventWaitHandle 进行线程交互(或线程信号)。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. 若要直接释放类型,请在 Disposetry/ 块中调用其 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 等待信号A thread waits for a signal by calling AutoResetEvent.WaitOne. 如果 AutoResetEvent 处于非终止状态,则线程将会阻塞,直到调用AutoResetEventIf 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.

如果线程在 AutoResetEvent 处于终止状态时调用 WaitOne,则线程不会阻塞。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. 此外,如果在没有等待的线程且 AutoResetEvent 已发出信号的情况下调用 Set,则调用不起作用。Also, if Set is called when there are no threads waiting and the AutoResetEvent is already signaled, the call has no effect.

您可以通过将布尔值传递到构造函数来控制 AutoResetEvent 的初始状态:如果初始状态为 "已终止",则为 true; 否则为 falseYou 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 还可以与 static WaitAllWaitAny 方法一起使用。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 在功能上等效于使用 EventResetMode.AutoReset创建的 EventWaitHandleAn 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.

构造函数

表 1
AutoResetEvent(Boolean)

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

字段

表 2
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.

(继承自 WaitHandle)

属性

表 3
Handle

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

(继承自 WaitHandle)
SafeWaitHandle

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

(继承自 WaitHandle)

方法

表 4
Close()

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

(继承自 WaitHandle)
CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(继承自 MarshalByRefObject)
Dispose()

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

(继承自 WaitHandle)
Dispose(Boolean)

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

(继承自 WaitHandle)
Equals(Object)

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

(继承自 Object)
GetAccessControl()

获取一个 EventWaitHandleSecurity 对象,它表示当前 EventWaitHandle 对象所表示的已命名系统事件的访问控件安全性。Gets an EventWaitHandleSecurity object that represents the access control security for the named system event represented by the current EventWaitHandle object.

(继承自 EventWaitHandle)
GetHashCode()

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

(继承自 Object)
GetLifetimeService()

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

(继承自 MarshalByRefObject)
GetType()

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

(继承自 Object)
InitializeLifetimeService()

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

(继承自 MarshalByRefObject)
MemberwiseClone()

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

(继承自 Object)
MemberwiseClone(Boolean)

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

(继承自 MarshalByRefObject)
Reset()

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

Reset()

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

(继承自 EventWaitHandle)
Set()

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

Set()

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

(继承自 EventWaitHandle)
SetAccessControl(EventWaitHandleSecurity)

设置已命名的系统事件的访问控制安全性。Sets the access control security for a named system event.

(继承自 EventWaitHandle)
ToString()

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

(继承自 Object)
WaitOne()

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

(继承自 WaitHandle)
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.

(继承自 WaitHandle)
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.

(继承自 WaitHandle)
WaitOne(TimeSpan)

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

(继承自 WaitHandle)
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.

(继承自 WaitHandle)

显式接口实现

表 5
IDisposable.Dispose()

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

(继承自 WaitHandle)

扩展方法

表 6
GetAccessControl(EventWaitHandle)
SetAccessControl(EventWaitHandle, EventWaitHandleSecurity)
GetSafeWaitHandle(WaitHandle)

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

SetSafeWaitHandle(WaitHandle, SafeWaitHandle)

设置本机操作系统等待句柄的安全句柄。

原文地址:https://www.cnblogs.com/2SBC/p/12900604.html