title: Thread-safe execution using System.Threading.Timer and Monitor
body: <p>Using a <code>System.Threading.Timer</code> results in threads being spun from a <code>ThreadPool</code>, which means if the interval of execution for the timer expires while a thread is still processing by order of a previous request, then the same callback will be delegated to execute on another thread. This is obviously going to cause problems in most cases unless the callback is re-entrant aware, but I'm wondering <em>how</em> to go about it the best (meaning safe) way.</p>
  
  <p>Let's say we have the following:</p>
  
  <pre><code>ReaderWriterLockSlim OneAtATimeLocker = new ReaderWriterLockSlim();
  
  OneAtATimeCallback = new TimerCallback(OnOneAtATimeTimerElapsed);
  OneAtATimeTimer = new Timer(OneAtATimeCallback , null, 0, 1000);
  </code></pre>
  
  <p>Should the whole shebang be be locked down, as such:</p>
  
  <pre><code>private void OnOneAtATimeTimerElapsed(object state)
  {
      if (OneAtATimeLocker.TryEnterWriteLock(0))
      {
          //get real busy for two seconds or more
  
          OneAtATimeLocker.ExitWriteLock();
      }
  }
  </code></pre>
  
  <p>Or, should only entry be managed, and kick out 'trespassers', as such:</p>
  
  <pre><code>private void OnOneAtATimeTimerElapsed(object state)
  {
      if (!RestrictOneAtATime())
      {
          return;
      }
  
      //get real busy for two seconds or more
  
      if(!ReleaseOneAtATime())
      {
          //Well, Hell's bells and buckets of blood!
      }       
  }
  
  bool OneAtATimeInProgress = false;
  
  private bool RestrictToOneAtATime()
  {
      bool result = false;
      if (OneAtATimeLocker.TryEnterWriteLock(0))
      {
          if(!OneAtATimeInProgress)
          {
              OneAtATimeInProgress = true;
              result = true;
          }
          OneAtATimeLocker.ExitWriteLock();
      }
      return result;
  }
  
  private bool ReleaseOneAtATime()
  {
      bool result = false;
      //there shouldn't be any 'trying' about it...
      if (OneAtATimeLocker.TryEnterWriteLock(0))
      {            
          if(OneAtATimeInProgress)
          {
              OneAtATimeInProgress = false;
              result = true;
          }
          OneAtATimeLocker.ExitWriteLock();
      }
      return result;
  }
  </code></pre>
  
  <p><em>Does the first have any performance implications because it locks for the extent of the method?</em></p>
  
  <p><em>Does the second even offer the safety one might think it does - is something escaping me?</em></p>
  
  <p><em>Are there any other ways to go about this reliably, and preferably?</em></p>