title: CancellationTokenRegistration.Dispose in Async Task
body: <p>I am making a <code>SocketExtender</code> class which will provide <code>async/await Task</code> extension methods to the <code>Socket</code> class. In my extension methods I am adding is the ability to cancel a <code>Socket</code> operation, such as <code>ConnectAsync</code>, <code>ReceiveAsync</code>, or <code>SendAsync</code> via a <code>CancellationToken</code> parameter.</p>
  
  <p>Doing some reading on the optimal way to do this, I have decided to wrap the calls in <code>TaskCompletionSource&lt;T&gt;</code> and pass back a <code>Task</code> for the operation.</p>
  
  <p>For example, I want to wrap the <code>BeginReceive</code> and <code>EndReceive</code> APM methods into the following <code>Task</code>-based method:</p>
  
  <pre><code>public static Task&lt;int&gt; ReceiveAsync(this Socket socket, byte[] buffer, int offset, int count, SocketFlags flags, CancellationToken token) 
  {
    var tcs = new TaskCompletionSource&lt;int&gt;();
  
    socket.BeginReceive(buffer, offset, count, flags, result =&gt; 
    {
      try
      {
        var bytesReceived = socket.EndReceive(result);
        tcs.SetResult(bytesReceived);
      }
      catch(Exception ex)
      {
        if(token.IsCancellationRequested)
          tcs.SetCanceled();  // &lt;- Yes, this is a typo in the .NET framework! :)
        else
          tcs.SetException(ex);
      }
  
    });
  
    return tcs.Task;
  }
  </code></pre>
  
  <p><strong>NOTE</strong>: The above method does <em>not</em> actually implement cancellation! Yes, it will handle it, but it will not cause the <code>Socket</code> to actually cancel the operation. So I need the <code>CancellationToken</code> to trigger a <code>Socket.Close()</code> call, via <code>token.Register()</code>. No biggie, but the question becomes <em>how</em> do I properly dispose of the <code>CancellationTokenRegistration</code> object returned?</p>
  
  <p>Here is my first thought:</p>
  
  <pre><code>public static Task&lt;int&gt; ReceiveAsync(this Socket socket, byte[] buffer, int offset, int count, SocketFlags flags, CancellationToken token) 
  {
    var tcs = new TaskCompletionSource&lt;int&gt;();
  
    using(token.Register(socket.Close))  // &lt;- Here we are ensuring disposal of the CTR
    {
      socket.BeginReceive(buffer, offset, count, flags, result =&gt; 
      {
        try
        {
          var bytesReceived = socket.EndReceive(result);
          tcs.SetResult(bytesReceived);
        }
        catch(Exception ex)
        {
          if(token.IsCancellationRequested)
            tcs.SetCanceled();  // &lt;- Yes, this is a typo in the .NET framework! :)
          else
            tcs.SetException(ex);
        }
      });
    }
  
    return tcs.Task;
  }
  </code></pre>
  
  <p><strong>However</strong>, my question is that will the <code>CancellationTokenRegistration</code> be disposed of via <code>using</code> before the asynchronous call completes? My first instinct wants to say <strong>yes</strong>, because the <code>socket.BeginReceive</code> call will not block and return immediately, causing the <code>using</code> statement to clean up once the method returns <code>tcs.Task</code>. </p>
  
  <p>But then again, maybe the C# compiler 'understands' what I am doing and will see there's an anonymous method executing in a child scope and some black magic will take place to make it work the way I want.</p>
  
  <p>Do I even need to care about disposing of the <code>CancellationTokenRegistration</code> here? Should I keep a reference to it and call <code>Dispose()</code> in the <code>finally</code> block instead? Or will this work as I want it to as is?</p>