Wednesday, August 20, 2008

Don’t use a dedicated thread to wait on a kernel object

One of the code patterns in the previous post showed that you don’t need a dedicated thread to execute a piece of code at regular intervals.

Likewise you don’t need a dedicated thread to wait on a kernel object (such as a mutex or an event). You can use the threadpool to do this:

   1: class Test
   2: {
   3:   // This method returns an event. Whenever the event will be set (by the caller of this 
   4:   // method), the 'EventWasSet' method will be executed.
   5:   public WaitHandle GetEvent()
   6:   {
   7:     AutoResetEvent m_Event = new AutoResetEvent(false);
   8:     ThreadPool.RegisterWaitForSingleObject(m_Event, EventWasSet, null, Timeout.Infinite,false);
   9:     return m_Event;
  10:   }
  11:  
  12:   void EventWasSet(object state, bool timeOut)
  13:   {
  14:     // This code will be executed on the threadpool when the event is set
  15:   }
  16: }

The RegisterWaitForSingleObject() method makes sure that the given method will be executed on a threadpool thread when the kernel object is signaled.

No comments: