In multithreaded applications, synchronizing the execution of threads is crucial to avoid race conditions and ensure that shared resources are accessed in a controlled manner. One way to achieve this synchronization in C# is by using the AutoResetEvent class. This article will explain how to use AutoResetEvent for thread synchronization, illustrated by practical examples.
What is AutoResetEvent?
AutoResetEvent is a synchronization primitive that can be used to manage the execution order of threads. It operates like a gate that is either open (signaled) or closed (non-signaled). When a thread calls WaitOne() on an AutoResetEvent that is not signaled, it blocks until another thread calls Set(), which signals the event and allows the waiting thread to proceed. Once a thread has passed through the gate, AutoResetEvent automatically resets to the non-signaled state, blocking any subsequent threads until Set() is called again.
Example 1. Coordinating Multiple Threads
In the next example, we'll demonstrate how to use AutoResetEvent to coordinate the execution of multiple threads. Here, we have three threads that need to run in a specific order: Thread 1, followed by Thread 2, and then Thread 3.
using System;
using System.Threading;
namespace MultiThreadSynchronization
{
class Program
{
private static AutoResetEvent event1 = new AutoResetEvent(false);
private static AutoResetEvent event2 = new AutoResetEvent(false);
static void Main(string[] args)
{
Thread t1 = new Thread(Thread1);
Thread t2 = new Thread(Thread2);
Thread t3 = new Thread(Thread3);
t1.Start();
t2.Start();
t3.Start();
// Start the first thread
event1.Set();
Console.Read();
}
static void Thread1()
{
event1.WaitOne();
Console.WriteLine("Thread 1 is running");
// Signal the second thread to start
event2.Set();
}
static void Thread2()
{
event2.WaitOne();
Console.WriteLine("Thread 2 is running");
// Signal the third thread to start
event1.Set();
}
static void Thread3()
{
event1.WaitOne();
Console.WriteLine("Thread 3 is running");
}
}
}
Example 2. Real-Life use case processing orders in sequence
Consider an e-commerce system where we need to process customer orders in sequence. Each order goes through several stages: validation, payment processing, and shipment. These stages should be executed in order, and each stage should start only when the previous stage is complete.

Comments
Join the conversation! Your thoughts help the community grow.