Sobes.tech
Junior — Middle

Can you explain how ManualResetEvent works and its purpose in programming?

sobes.tech AI

Answer from AI

ManualResetEvent is a synchronization primitive in .NET used for thread management. It represents an event that can be in a signaled or non-signaled state.

Main features:

  • When the event is in a signaled state, all waiting threads are unblocked and continue execution.
  • Unlike AutoResetEvent, ManualResetEvent remains in a signaled state until it is explicitly reset using the Reset() method.

Usage:

ManualResetEvent is useful when you need to unblock multiple threads simultaneously and keep the event in a signaled state until a certain condition is met.

Example:

ManualResetEvent manualEvent = new ManualResetEvent(false); // Initially non-signaled

// Thread 1
ThreadPool.QueueUserWorkItem(_ => {
    Console.WriteLine("Waiting for event...");
    manualEvent.WaitOne(); // Waits for the signal
    Console.WriteLine("Event received, continuing work.");
});

// Somewhere in the code, when you need to unblock threads
manualEvent.Set(); // Sets the event to a signaled state

// To block the threads again
manualEvent.Reset();

Thus, ManualResetEvent allows controlling thread execution by synchronizing multiple threads with a signal event that is not automatically reset.

Can you explain how ManualResetEvent works and its… - sobes.tech