title: C# - TcpClient asynchronous connection with specific time duration
body: <p>I am trying to create a function that try to asynchronously connect to a host during a specific time and then check if the connection have been made.</p>
  
  <p>My problem is that I am not able to add a duration for this asynchronous connection.</p>
  
  <p>My function:</p>
  
  <pre><code> public async Task&lt;bool&gt; IsConnected()
   {
          // Host IP Address and communication port
          string ipAddress = "192.168.0.11";
          int port = 9100;
  
          //Try to Connect with the host during 2 second
          {
              // Create TcpClient and try to connect
              using (TcpClient client = new TcpClient())
              { 
                  Task&lt;bool&gt; mytask = client.ConnectAsync(ipAddress, port).Wait(TimeSpan.FromSeconds(2));
                  bool isconnected = await mytask;
  
                  if (isconnected)
                  {
                      //Connection with host
                      return true;
                  }
                  else
                  {
                      // No connection with host
                      return false;
                  }
                  //Close Connection
                  client.Close();
              }
          }
          catch (Exception exception)
          {
              // Problem with connection
              return false;
          }
  }
  </code></pre>
  
  <p>I have this error:</p>
  
  <pre><code>Cannot implicitly convert type 'bool' to 'System.Threading.Tasks.Task&lt;bool&gt;' at line :
  
  Task&lt;bool&gt; mytask = client.ConnectAsync(ipAddress, port).Wait(TimeSpan.FromSeconds(2));
  </code></pre>
  
  <p>I have searched everywhere and didn't have found a solution.</p>
  
  <p>Thanks for the help</p>
  
  <p>Daniel</p>
  
  <p>WORKING SOLUTION : </p>
  
  <pre><code> public async Task&lt;bool&gt; IsConnected()
   {
          // Host IP Address and communication port
          string ipAddress = "192.168.0.11";
          int port = 9100;
  
          //Try to Connect with the host during 2 second
          {
              // Create TcpClient and try to connect
              using (TcpClient client = new TcpClient())
              { 
                  //Create Tasks
                  var clientTask = client.ConnectAsync(ipAddress, port);
                  var delayTask = Task.Delay(2000);
  
                  //Check which one finish first
                  var completedTask = await Task.WhenAny(new[] {clientTask, delayTask});
  
                  //Check if the connection have been established before the end of the timer 
                  return completedTask == clientTask;
              }
          }
          catch (Exception exception)
          {
              // Problem with connection
              return false;
          }
  }
  </code></pre>