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 一次釋放一個執行緒,方式是透過每次使用者按下 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.\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)

使用布林值 (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)

建立包含所有相關資訊的物件,這些資訊是產生用來與遠端物件通訊的所需 Proxy。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 所使用的 Unmanaged 資源,並選擇性釋放 Managed 資源。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()

擷取控制這個執行個體存留期 (Lifetime) 原則的目前存留期服務物件。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 的淺層複本 (Shallow Copy)。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

取得或設定原生 (Native) 的作業系統控制代碼。Gets or sets the native operating system handle.

(Inherited from WaitHandle)
SafeWaitHandle SafeWaitHandle SafeWaitHandle SafeWaitHandle

取得或設定原生 (Native) 的作業系統控制代碼。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.

另請參閱