title: Self-disposing timer
body: <p>How can I automatically dispose of, and nullify, a timer after it's elapsed?</p>
  
  <p>The <code>sender</code> is a random object with no method; I can't dynamically access the original timer via the EventHandler.</p>
  
  <p>Another function will want to check if this timer is null, or running (and interrupt it).</p>
  
  <p>I could run logic such as:</p>
  
  <p><code>if (timer != null &amp;&amp; timer.Enabled)</code> but I'd rather <code>if (timer != null)</code></p>
  
  <p>I could also instantiate the variable with a dummy timer, and simply check if this is enabled, but I know if this variable were to suddenly become null, the program would crash.</p>
  
  <p>Should I just use the prior if statement; won't these timers in memory start to add up?</p>
  
  <p>EDIT: </p>
  
  <pre><code>static void Main()
  {
      Timer timer = null;
      timer = new Timer(5000);
      timer.Elapsed += (sender, e) =&gt; {
          var T = (Timer)sender;
          T.Dispose();
          T = null;
          Console.WriteLine(T);
      };
      timer.Start();
  
      while (true)
      {
          Console.WriteLine(timer);
          System.Threading.Thread.Sleep(1000);
      }
  }
  </code></pre>