This advanced design pattern show how one thread can wait to be signalled from another thread, and to time out after a specified period.
A thread that periodically performs a task, but can be signalled to terminate from another thread:
// required for AutoResetEvent class
using System.Threading;
// initialize an event object
private AutoResetEvent quitEvent = new AutoResetEvent( false );
private void SendHeartbeat()
{
// wait 10 seconds for the event object to become signalled
while( quitEvent.WaitOne( 10000, false ) == false )
{
// the wait timed out: send the heartbeat message, and continue waiting
this.Logger.Debug( "Sending heartbeat" );
}
// the event was signaled; exit this thread
this.Logger.Debug( "Signaled to quit; exiting thread." );
}
private void StopHeartbeat()
{
// signal to the heartbeat thread to terminate
quitEvent.Set();
}
This design pattern:
declares an AutoResetEvent object quitEvent, and set its initial state to non-signaled,
the SendHeartbeat method waits for 10,000ms (10 seconds) for the quitEvent object to become signaled,
if the WaitOne operation times out (i.e. returns false) the method displays a heartbeat message, and re-enters the while loop,
if the quitEvent is signaled, the while loop breaks and the method displays a quit message; the method exits, terminating the thread,
the StopHeartbeat method can be called from another thread, and sets the quitEvent object to signaled.