title: Stopping timer in its callback method
body: <p>I have a System.Threading.Timer that calls its appropriate event handler (callback) every <strong>10 ms</strong>. The method itself is <strong>not reentrant</strong> and can sometimes take <strong>way longer than 10 ms</strong>. Thus, I want to stop the timer during method execution.</p>
  
  <p>Code:</p>
  
  <pre><code>private Timer _creatorTimer;
  
  // BackgroundWorker's work
  private void CreatorWork(object sender, DoWorkEventArgs e) {
        _creatorTimer = new Timer(CreatorLoop, null, 0, 10);
  
        // some other code that worker is doing while the timer is active
        // ...
        // ...
  }
  
  private void CreatorLoop(object state) {
        // Stop timer (prevent reentering)
        _creatorTimer.Change(Timeout.Infinite, 0);
  
        /*
            ... Work here
        */
  
        // Reenable timer
        _creatorTimer.Change(10, 0);
  } 
  </code></pre>
  
  <p>MSDN states that the callback method is called (every time the timer fires) in separate thread from the thread pool. That means that if I stop the timer the first thing in method it still doesn't neccessarily prevent the timer to fire and run another instance of the method before the first one had a chance to stop the timer.</p>
  
  <p>Should maybe the timer (or even the non-reentrant method itself) be locked?
  What is the right way to prevent timer from firing during execution of its callback (and non-reentrant) method?</p>