Wait for AutoResetEvent Pattern

This advanced design pattern show how one thread can wait to be signalled from another thread, and to time out after a specified period.

 

Pattern Syntax

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();

}

 

 

Remarks

This design pattern:

 

See Also

Multithreading

Design Patterns Index