title: C# TcpClient Connection Retry
body: <p>I don't understand what information I have available to me with async operations in C# even after reading the docs. I have a TpcClient and I want it to try to connect x number of times. So far:</p>
  
  <pre><code>    public async Task SocketConnect() {
          tcpClient = new TcpClient();
          for(int i = 0; i &lt; maxConnectionAttempts; i++) {
              OpenSocket();
              await Task.Delay(5000);
          }
      }
  
      private void OpenSocket() {
          try {
              tcpClient.BeginConnect(host, port, ConnectCallback, tcpClient);
          }
          catch (Exception e) {
              Console.WriteLine(e.ToString());
          }
      }
  
      private void ConnectCallback(IAsyncResult result) {
          try {
              tcpClient.EndConnect(result);
  
              // Connected
              if (tcpClient.Connected) {
                  Console.WriteLine("connected");
                  if (OnClientEvent != null)
                      OnClientEvent(this, new ClientEventArgs(Action.Connect));
  
                  stream = tcpClient.GetStream();
  
                  BeginReadAsync();
              }
              // Not connected
              else {
                  Console.WriteLine("not connected");
                  Console.WriteLine("Retrying");
              }
          }            
          catch (Exception e) {
              Console.WriteLine(e.ToString());
          }
      }
  </code></pre>
  
  <p>I'm missing the logic in the <code>SocketConnect()</code> method. I'm not sure how I could <code>await</code> <code>OpenSocket()</code> because its result is carried to a different callback. What can I return from <code>OpenSocket()</code> so that I know it connected?</p>