AutoResetEvent
yesC#
A synchronization primitive in used to pass signals between threads. When the thread callsAutoResetEvent
ofWaitOne
When a method is called, it will block until another thread callsSet
Method to release it. OnceWaitOne
Method returns,AutoResetEvent
Its status will be reset automatically, which means the next callWaitOne
The thread will block again untilSet
Called again.
Here is an example of its simple purpose:
using System; using ; class Program { static AutoResetEvent autoEvent = new AutoResetEvent(false); static void Main() { Thread thread1 = new Thread(DoWork); (); // Wait for a while to make sure thread1 has started executing and blocking in (); (1000); // Release thread1 to continue execution (); (); } static void DoWork() { ("Thread is waiting..."); (); // The thread will block here until () is called ("Thread has been released and is now doing work..."); } }
In the example above, we created aAutoResetEvent
Instance and set its initial state tofalse
. Then, we started a new thread to executeDoWork
method. In this method, the thread calls()
and block. The main thread waits for a while to make sure that the DoWork method has started executing and blocking, and then calls()
To release it. OnceSet
Called,DoWork
The method ofWaitOne
It will return, the thread will continue to execute and output the message.
andManualResetEvent
different,AutoResetEvent
Reset immediately after a waiting thread is released, which means the next callWaitOne
The thread will block again untilSet
Called again. andManualResetEvent
Without explicit callReset
The method will maintain its state (whether it istrue
stillfalse
)。
This is the end of this article about the specific usage of C# AutoResetEvent. For more related C# AutoResetEvent content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!