Junior — Middle
Explain what AutoResetEvent is and how it is used for thread synchronization in .NET.
sobes.tech AI
Answer from AI
AutoResetEvent is a class in .NET used for thread synchronization. It represents an event that automatically resets to a non-signaled state after one waiting thread has been released.
Working principle:
- Initially, AutoResetEvent is in a signaled (set) or non-signaled (reset) state.
- If a thread calls the WaitOne() method and the event is in a signaled state, the thread continues to work, and the event automatically transitions to a non-signaled state.
- If the event is in a non-signaled state, the thread blocks until someone calls Set(), which transitions the event to a signaled state.
This allows implementing a mechanism where one thread signals another that it can continue working, and it guarantees that the signal will be processed by only one thread.
Example of usage:
AutoResetEvent autoEvent = new AutoResetEvent(false);
void Worker()
{
Console.WriteLine("Waiting for signal...");
autoEvent.WaitOne(); // Wait for the signal
Console.WriteLine("Signal received, continuing work.");
}
// In another thread
void Signaler()
{
Thread.Sleep(1000); // Simulate work
autoEvent.Set(); // Send a signal to one waiting thread
}