2009 Advent Calendar December 20th

But wait! What happened yesterday? We added some significant functionality; hiding the fact that AbandonedMutexException might be thrown. Because of this I want to break out the Mutex implementation into a separate, thin wrapper for the Mutex object:

    1:      public class MutexWrapper
   2:      {
   3:          private readonly Mutex _lock = new Mutex();
   4:   
   5:          public void WaitOne() 
   6:          {
   7:              _lock.WaitOne(); 
   8:          }
   9:   
  10:          public void ReleaseMutex()
  11:          {
  12:              _lock.ReleaseMutex();
  13:          }
  14:      }

Given that I use generics to inject the dependency:

    1:      public class MutexLock<T> : Lock where T : MutexWrapper, new()
   2:      {
   3:          private readonly T _lock = new T();
   4:   
   5:          public void Lock()
   6:          {
   7:              try
   8:              {
   9:                  _lock.WaitOne();
  10:              }
  11:              catch (AbandonedMutexException) { }
  12:          }
  13:   
  14:          public void Unlock()
  15:          {
  16:              _lock.ReleaseMutex();
  17:          }
  18:      }

I'll spare you the changes needed to make the tests compile for now since the use of MutexWrapper makes it possible to remove all those helper threads and slow tests for the MutexLock class.