title: Cancellation support for TcpClient.ConnectAsync method
body: <p>I am hoping to get some opinions on adding resilience to a piece that I am working on that involves creating multiple <code>TcpClient</code> connections asynchronously to various servers and once the TCP connections are successfully established, then storing the <code>TcpClient</code> in sort of a collection (Just an excerpt from the requirement)</p>
  
  <p>This is what I have so far:</p>
  
  <pre><code>internal class Program
  {
      private static readonly TcpClient _client = new TcpClient(AddressFamily.InterNetwork);
      private static SslStream _stream;
  
      private static async Task Main(string[] args)
      {
          var timeoutTask = Task.Delay(5000);
          var connectTask = _client.ConnectAsync("10.14.16.24", 56564);
  
          var completedTask = await Task.WhenAny(timeoutTask, connectTask);
          if (completedTask == timeoutTask)
              _client.Dispose();
  
          try
          {
              await connectTask;
              _stream = new SslStream(_client.GetStream(), false);
          }
          catch (SocketException e)
          {
              Console.WriteLine(e.Message);
          }
      }
  }
  </code></pre>
  
  <p><strong>Question</strong>:
  In case a timeout happens, the <code>connectTask</code> status is still "<code>WaitingForActivation</code>" until the <code>ConnectAsync</code> method returns either <code>Faulted</code> or <code>RanToCompletion</code>. How to cancel this task, knowing that <code>ConnectAsync</code> doesn't support <code>CancellationToken</code></p>
  
  <p>Any suggestions, or improvements are welcome.
  Thanks</p>