Thursday, February 21, 2008

.NET Threading - AutoResetEvent And ManualResetEvent

In .NET EventWait handles are used for signaling for threads' communication. Signaling is when one thread waits until it receives notification from another. AutoResetEvent and ManualResetEvent are two EventWait handles available in .NET 2.0. AutoRsetEvent allows a thread to unblock once when it receives a signal from another and then it automatically resets. ManualResetEvent won't do reset by itself unless you do it manually. Following code sample demos such concept:
using System;
using System.Threading;

class Test
{
static void Main()
{
AutoResetEvent autoReset = new AutoResetEvent(false);
ManualResetEvent manualReset = new ManualResetEvent(false);
WaitHandle[] events = new WaitHandle[2] { autoReset, manualReset };

//Start 3 threads with AutoResetEvent
for (int i = 0; i < 3; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(Run), autoReset);
}
Thread.Sleep(1000);
autoReset.Set();
Thread.Sleep(1000);
Console.WriteLine();

//Start 3 threads with ManualResetEvent
for (int i = 0; i < 3; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback(Run), manualReset);
}
Thread.Sleep(1000);
manualReset.Set();
Thread.Sleep(1000);

Console.WriteLine("\nMain thread completed...");
Console.ReadLine();
}

static void Run(object obj)
{
EventWaitHandle hander = obj as EventWaitHandle;
Console.WriteLine("Thread {0} is started and blocked...", Thread.CurrentThread.ManagedThreadId);
hander.WaitOne();
Console.WriteLine("Thread {0} is unblocked...", Thread.CurrentThread.ManagedThreadId);
}
}
Result: