Wait for AutoResetEvent Pattern

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

 

Pattern Syntax

For a thread to signal to a waiting thread that there is work to do:

 

 

// required for AutoResetEvent class

using System.Threading;

 

// initialize an event object

private AutoResetEvent dataReadyEvent = new AutoResetEvent( false );

 

private byte[] dataToProcess;

 

private void ReceiveData( byte[] data )

{

   // copy the received data

   dataToProcess = data.CopyTo( dataToProcess );

   

   // signal to the waiting thread that there is data to process

   dataReadyEvent.Set();

}

 

private void ProcessData()

{

   // wait indefinitely for the event object to become signalled

   while( dataReadyEvent.WaitOne( System.Threading.Timeout.Infinite, false ) )

   {

      if( dataToProcess.Length == 0 )

      {

         // there is no data to process; exit this thread

         this.Logger.Debug( "No data to process; exiting thread." );

         return;

      }

      else

      {

         // display the data and continue waiting

         for( int i = 0; i < dataToProcess.Length; i++ )

         {

            this.Logger.Debug( String.Format( "byte {0} = {1:X2}", i, dataToProcess[i] ) );

         }

      }

   }

}

 

 

Remarks

This design pattern:

 

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