title: Why is my async/await with CancellationTokenSource leaking memory?
body: <p>I have a .NET (C#) application that makes extensive use of async/await. I feel like I've got my head around async/await, but I'm trying to use a library (RestSharp) that has an older (or perhaps I should just say different) programming model that uses callbacks for asynchronous operations.</p>
  
  <p>RestSharp's <code>RestClient</code> class has an ExecuteAsync method that takes a callback parameter, and I wanted to be able to put a wrapper around that which would allow me to <code>await</code> the whole operation. The <code>ExecuteAsync</code> method looks something like this:</p>
  
  <pre><code>public RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action&lt;IRestResponse&gt; callback);
  </code></pre>
  
  <p>I thought I had it all working nicely. I used <code>TaskCompletionSource</code> to wrap the <code>ExecuteAsync</code> call in something that I could await, as follows:</p>
  
  <pre><code>public static async Task&lt;T&gt; ExecuteRequestAsync&lt;T&gt;(RestRequest request, CancellationToken cancellationToken) where T : new()
  {
      var response = await ExecuteTaskAsync(request, cancellationToken);
  
      cancellationToken.ThrowIfCancellationRequested();
  
      return Newtonsoft.Json.JsonConvert.DeserializeObject&lt;T&gt;(response.Content);
  }
  
  private static async Task&lt;IRestResponse&gt; ExecuteTaskAsync(RestRequest request, CancellationToken cancellationToken)
  {
      var taskCompletionSource = new TaskCompletionSource&lt;IRestResponse&gt;();
  
      var asyncHandle = _restClient.ExecuteAsync(request, r =&gt; 
      {
          taskCompletionSource.SetResult(r); 
      });
  
      cancellationToken.Register(() =&gt; asyncHandle.Abort());
  
      return await taskCompletionSource.Task;
  }
  </code></pre>
  
  <p>This has been working fine for most of my application.</p>
  
  <p>However, I have one part of the application that does hundreds of calls to my <code>ExecuteRequestAsync</code> as part of a single operation, and that operation shows a progress dialog with a cancel button. You'll see that in the code above that I'm passing a <code>CancellationToken</code> to <code>ExecuteRequestAsync</code>; for this long-running operation, the token is associated with a <code>CancellationTokenSource</code> "belonging" to the dialog, whose <code>Cancel</code> method is called if the use clicks the cancel button. So far so good (the cancel button does work).</p>
  
  <p>My problem is that my application's memory usage shoots up during the long-running application, to the extent that it runs out of memory before the operation completes.</p>
  
  <p>I've run a memory profiler on it, and discovered that I have lots of <code>RestResponse</code> objects still in memory, even after garbage collection. (They in turn have huge amounts of data, because I'm sending multi-megabyte files across the wire).</p>
  
  <p>According to the profiler, those <code>RestResponse</code> objects are being kept alive because they're referred to by the <code>TaskCompletionSource</code> (via the <code>Task</code>), which in turn is being kept alive because it's referenced from the <code>CancellationTokenSource</code>, via its list of registered callbacks.</p>
  
  <p>From all this, I gather that registering the cancellation callback for each request means that the whole graph of objects that is associated with all those requests will live on until the entire operation is completed. No wonder it runs out of memory :-)</p>
  
  <p>So I guess my question is not so much "why does it leak", but "how do I stop it". I can't <em>un</em>-register the callback, so what <em>can</em> I do? </p>