title: Best way to create a "run-once" time delayed function in C#
body: <p>I am trying to create a function that takes in an Action and a Timeout, and executes the Action after the Timeout.  The function is to be non-blocking.  The function must be thread safe.  I also really, really want to avoid Thread.Sleep().</p>
  
  <p>So far, the best I can do is this:</p>
  
  <pre><code>long currentKey = 0;
  ConcurrentDictionary&lt;long, Timer&gt; timers = new ConcurrentDictionary&lt;long, Timer&gt;();
  
  protected void Execute(Action action, int timeout_ms)
  {
      long currentKey = Interlocked.Increment(ref currentKey);
      Timer t = new Timer(
        (key) =&gt;
           {
             action();
             Timer lTimer;
             if(timers.TryRemove((long)key, out lTimer))
             {
                 lTimer.Dispose();
             }
           }, currentKey, Timeout.Infinite, Timeout.Infinite
        );
  
       timers[currentKey] = t;
       t.Change(timeout_ms, Timeout.Infinite);
  }
  </code></pre>
  
  <p>The problem is that calling Dispose() from the callback itself cannot be good.  I am unsure if it is safe to "fall off" the end, i.e. Timers are considered live while their lambdas are executing, but even if this is the case I'd rather dispose it properly.</p>
  
  <p>The "fire once with a delay" seems like such a common problem that there should be an easy way to do this, probably some other library in System.Threading I am missing, but right now the only solution I can think of is modification of the above with a dedicated cleanup task running on an interval.  Any advice?</p>