title: Single threaded timer
body: <p>I wanted a timer with the following properties:</p>
  <ol>
  <li><p>No matter how many times start is called, only one call back thread is ever running</p>
  </li>
  <li><p>The time spent in the call back function was ignored with regards to the interval. E.g if the interval is 100ms and the call back takes 4000ms to execute, the callback is called at 100ms, 4100ms etc.</p>
  </li>
  </ol>
  <p>I couldn't see anything available so wrote the following code. Is there a better way to do this?</p>
  <pre><code>/**
   * Will ensure that only one thread is ever in the callback
   */
  public class SingleThreadedTimer : Timer
  {
      protected static readonly object InstanceLock = new object();
      
      //used to check whether timer has been disposed while in call back
      protected bool running = false;
  
      virtual new public void Start()
      {
          lock (InstanceLock)
          {
              this.AutoReset = false;
              this.Elapsed -= new ElapsedEventHandler(SingleThreadedTimer_Elapsed);
              this.Elapsed += new ElapsedEventHandler(SingleThreadedTimer_Elapsed);
              this.running = true;
              base.Start();
          }
          
      }
  
      virtual public void SingleThreadedTimer_Elapsed(object sender, ElapsedEventArgs e)
      {
          lock (InstanceLock)
          {
              DoSomethingCool();
  
              //check if stopped while we were waiting for the lock,
              //we don't want to restart if this is the case..
              if (running)
              {
                  this.Start();
              }
          }
      }
  
      virtual new public void Stop()
      {
          lock (InstanceLock)
          {
              running = false;
              base.Stop();
          }
      }
  }
  </code></pre>