AutoResetEvent Signalling
This example can be used where
two workers are sharing / exchanging work
Traffic signalling
Typically in this pattern two threads share the work
static AutoResetEvent FirstWorktodo = new AutoResetEvent(false);
static AutoResetEvent SecondWorkTodo = new AutoResetEvent(false);
int Main()
{
Console.WriteLine("starting two threads");
ThreadPool.QueueUserWorkItem(FirstWork);
ThreadPool.QueueUserWorkItem(SecondWork);
FirstWorktodo.Set(); // signal the firstOne to begin with
}
static void FirstWork(object o)
{
while (true)
{
FirstWorktodo.WaitOne();
Console.WriteLine("FirstWork starting.");
Thread.Sleep(2000);
Console.WriteLine("FirstWork ending.");
SecondWorkTodo.Set();
}
}
static void SecondWork(object o)
{
while (true)
{
SecondWorkTodo.WaitOne();
Console.WriteLine("secondWork starting.");
Thread.Sleep(2000);
Console.WriteLine("SecondWork ending.");
FirstWorktodo.Set();
}
}
starting two threads
FirstWork starting.
FirstWork ending.
secondWork starting.
SecondWork ending.
FirstWork starting.
FirstWork ending.
secondWork starting.
SecondWork ending..........
static AutoResetEvent SecondWorkTodo = new AutoResetEvent(false);
static AutoResetEvent FirstWorktodo = new AutoResetEvent(false);
static AutoResetEvent ThirdWorktodo = new AutoResetEvent(false);
static AutoResetEvent FourthWorktodo = new AutoResetEvent(false);
static void FirstWork(object o)
{
while (true)
{
FirstWorktodo.WaitOne();
Console.WriteLine("FirstWork starting.");
Thread.Sleep(2000);
Console.WriteLine("FirstWork ending.");
SecondWorkTodo.Set();
}
}
static void SecondWork(object o)
{
while (true)
{
SecondWorkTodo.WaitOne();
Console.WriteLine(" SecondWork starting.");
Thread.Sleep(2000);
Console.WriteLine(" SecondWork ending.");
ThirdWorktodo.Set();
}
}
static void ThirdWork(object o)
{
while (true)
{
ThirdWorktodo.WaitOne();
Console.WriteLine(" ThirdWork starting.");
Thread.Sleep(2000);
Console.WriteLine(" ThirdWork ending.");
FourthWorktodo.Set();
}
}
static void FourthWork(object o)
{
while (true)
{
FourthWorktodo.WaitOne();
Console.WriteLine(" FourthWork starting.");
Thread.Sleep(2000);
Console.WriteLine(" FourthWork ending.");
FirstWorktodo.Set();
}
}
int main()
{
Console.WriteLine("starting two threads");
ThreadPool.QueueUserWorkItem(FirstWork);
ThreadPool.QueueUserWorkItem(SecondWork);
ThreadPool.QueueUserWorkItem(ThirdWork);
ThreadPool.QueueUserWorkItem(FourthWork);
FirstWorktodo.Set();
}
starting two threads
FirstWork starting.
FirstWork ending.
SecondWork starting.
SecondWork ending.
ThirdWork starting.
ThirdWork ending.
FourthWork starting.
FourthWork ending.
FirstWork starting.
FirstWork ending.
SecondWork starting.
SecondWork ending.
ThirdWork starting.
ThirdWork ending.
FourthWork starting.
...............