title: Is CancellationTokenSource.CancelAfter() leaky?
body: <p>The release of the <a href="http://www.microsoft.com/en-us/download/details.aspx?id=29576" rel="noreferrer">Async Targeting Pack</a> prompted me to use <a href="http://wiki.sharpdevelop.net/ILSpy.ashx" rel="noreferrer">ILSpy</a> to have a look at what <a href="http://www.microsoft.com/en-us/download/details.aspx?id=19957" rel="noreferrer">Task-based Asynchronous Pattern (TAP)</a> extension methods were provided there (some of which I have already implemented on my own for use in VS2010). I stumbled upon the <a href="http://msdn.microsoft.com/en-us/library/system.threading.cancellationtokensource.cancelafter%28v=vs.110%29.aspx" rel="noreferrer"><code>.CancelAfter(TimeSpan)</code></a> method for <code>CancellationTokenSource</code> (which is as an extension method in the Async Targeting Pack for .NET 4.0 but is an instance method in .NET 4.5) and thought it could be a nice way to implement a timeout for various operations that don't natively have a timeout, but do support cancellation.</p>
  
  <p>But looking at the implementation in the Async Targeting Pack, it seems that if the associated <code>Task</code> completes or is canceled, the timer keeps on running.</p>
  
  <pre><code>/// &lt;summary&gt;Cancels the &lt;see cref="T:System.Threading.CancellationTokenSource" /&gt; after the specified duration.&lt;/summary&gt;
  /// &lt;param name="source"&gt;The CancellationTokenSource.&lt;/param&gt;
  /// &lt;param name="dueTime"&gt;The due time in milliseconds for the source to be canceled.&lt;/param&gt;
  public static void CancelAfter(this CancellationTokenSource source, int dueTime)
  {
      if (source == null)
      {
          throw new NullReferenceException();
      }
      if (dueTime &lt; -1)
      {
          throw new ArgumentOutOfRangeException("dueTime");
      }
      Timer timer = new Timer(delegate(object self)
      {
          ((IDisposable)self).Dispose();
          try
          {
              source.Cancel();
          }
          catch (ObjectDisposedException)
          {
          }
      });
      timer.Change(dueTime, -1);
  }
  </code></pre>
  
  <p>Let's say I  use this method to provide a timeout for a frequently used TAP-based operation, and wrap it with a <code>.CancelAfter()</code>. Now let's say the user provides a timeout value of 5 minutes (300 seconds), and calls this operation 100 times a second, which all complete successfully after a few milliseconds. After 300 seconds of 100 calls per second, 30,000 running timers would have accumulated from all those operations, even though the tasks completed successfully long ago. They would all eventually elapse and run the above delegate, which will probably throw an <code>ObjectDisposedException</code>, etc.</p>
  
  <p>Isn't this somewhat of a leaky, non-scalable behavior? When I implemented a timeout, I used <code>Task/TaskEx.Delay(TimeSpan, CancellationToken)</code> and when the associated task has ended, I cancel the <code>.Delay()</code> so that the timer would be stopped and disposed (it is an IDisposable after all, and it does contain unmanaged resources). Is this cleanup overly zealous? Is the cost of having tens of thousands of timers running simultaneously (and possibly throwing tens of thousands of caught exceptions later) really inconsequential to performance for the average application? Is the overhead and leakiness of <code>.CancelAfter()</code> almost always minuscule compared to the actual work being done, and should generally be disregarded?</p>