AutoResetEvent is one of the easy synchronization primitives in .NET threading synchronization.
AutoResetEvent is used for send signals between two threads.
Both threads share the same AutoResetEvent object. Thread can enter into a wait state by calling WaitOne() method of AutoResetEvent object. When second thread calls the Set() method it unblocks the waiting thread.
How AutoResetEvent Works
AutoResetEvent maintains a boolean variable in memory. If the boolean variable is false then it blocks the thread and if the boolean variable is true it unblocks the thread.
When we instantiate an AutoResetEvent object, we pass the default value of boolean value in the constructor. Below is the syntax of instantiate an AutoResetEvent object.
AutoResetEvent autoResetEvent = new AutoResetEvent(false);
WaitOne method
This method blocks the current thread and wait for the signal by other thread. WaitOne method puts the current thread into a Sleep thread state. WaitOne method returns true if it receives the signal else returns false.
autoResetEvent.WaitOne();
Second overload of WaitOne method wait for the specified number of seconds. If it does not get any signal thread continues its work.
static void ThreadMethod()
{
while(!autoResetEvent.WaitOne(TimeSpan.FromSeconds(2)))
{
Console.WriteLine("Continue");
Thread.Sleep(TimeSpan.FromSeconds(1));
}
Console.WriteLine("Thread got signal");
}
We called WaitOne method by passing the 2 seconds as arguments. In the while loop, it wait for the signal for 2 seconds then it continues its work. When the thread got the signal WaitOne returns true and exits the loop and print the “Thread got signal”.
Set method
AutoResetEvent Set method sent the signal to the waiting thread to proceed its work. Below is the syntax of calling Set method.
autoResetEvent.Set();
AutoResetEvent Example
The following example shows how to use AutoResetEvent to release one thread. In the Main method, we start a new thread by using Task Factory. It calls the GetDataFromServer method. After starting the method we put the main thread into wait state by calling WaitOne method on AutoResetEvent object. When from the GetDataFromServer method, we calls the Set method on AutoResetEvent object, it releases the main thread and print the dataFromServer into the console.
class Program
{
static AutoResetEvent autoResetEvent = new AutoResetEvent(false);
static string dataFromServer = "";
static void Main(string[] args)
{
Task task = Task.Factory.StartNew(() =>
{
GetDataFromServer();
});
//Put the current thread into waiting state until it receives the signal
autoResetEvent.WaitOne();
//Thread got the signal
Console.WriteLine(dataFromServer);
}
static void GetDataFromServer()
{
//Calling any webservice to get data
Thread.Sleep(TimeSpan.FromSeconds(4));
dataFromServer = "Webservice data";
autoResetEvent.Set();
}
}