SoFunction
Updated on 2025-04-06

Specific usage method of C# AutoResetEvent

AutoResetEventyesC#A synchronization primitive in  used to pass signals between threads. When the thread callsAutoResetEventofWaitOneWhen a method is called, it will block until another thread callsSetMethod to release it. OnceWaitOneMethod returns,AutoResetEventIts status will be reset automatically, which means the next callWaitOneThe thread will block again untilSetCalled 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 aAutoResetEventInstance and set its initial state tofalse. Then, we started a new thread to executeDoWorkmethod. 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. OnceSetCalled,DoWorkThe method ofWaitOneIt will return, the thread will continue to execute and output the message.

andManualResetEventdifferent,AutoResetEventReset immediately after a waiting thread is released, which means the next callWaitOneThe thread will block again untilSetCalled again. andManualResetEventWithout explicit callResetThe method will maintain its state (whether it istruestillfalse)。

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!