title: C# - What's the best way to use TcpListener (async)
body: <p>I would create a tcp server with TcpListener, but I don't know what's the best solution to do that.
  I tried with 3 examples. See below.</p>
  
  <p><strong>Example 1</strong>
  (I used BeginAcceptTcpClient)</p>
  
  <pre><code>class Program
    {
      static void Main(string[] args)
      {
        var endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4567);
        var listener = new TcpListener(endPoint);
  
        listener.Start();
  
        AcceptTcpClient(listener);
        while (true)
        {
        }
      }
  
      public static void AcceptTcpClient(TcpListener listener)
      {
        listener.BeginAcceptTcpClient(ClientConnected, listener);
      }
  
      public static void ClientConnected(IAsyncResult asyncResult)
      {
        var listener = (TcpListener)asyncResult.AsyncState;
        var client = listener.EndAcceptTcpClient(asyncResult);
        AcceptTcpClient(listener);
  
        DoAsync(client);
      }
    }
  </code></pre>
  
  <p><strong>Example 2</strong>
  (I used BeginAcceptTcpClient with AutoResetEvent)</p>
  
  <pre><code>class Program1
    {
      private static readonly AutoResetEvent CONNECTION_WAIT_HANDLE = new AutoResetEvent(false);
      static void Main(string[] args)
      {
        var endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4567);
        var listener = new TcpListener(endPoint);
  
        listener.Start();
  
        while (true)
        {
          listener.BeginAcceptTcpClient(ClientConnectedHandle, listener);
          CONNECTION_WAIT_HANDLE.WaitOne();
          CONNECTION_WAIT_HANDLE.Reset();
        }
      }
  
      public static void ClientConnectedHandle(IAsyncResult asyncResult)
      {
        var listener = (TcpListener)asyncResult.AsyncState;
        var client = listener.EndAcceptTcpClient(asyncResult);
        CONNECTION_WAIT_HANDLE.Set();
  
        DoAsync(client);
      }
    }
  </code></pre>
  
  <p><strong>Example 3</strong>
  (I used AcceptTcpClientAsync)</p>
  
  <pre><code>class Program2
    {
      static async Task Main(string[] args)
      {
        var endPoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 4567);
        var listener = new TcpListener(endPoint);
  
        listener.Start();
  
        while (true)
        {
          var client = await listener.AcceptTcpClientAsync();
          DoAsync(client);
        }
      }
  
      public static void AcceptTcpClient(TcpListener listener)
      {
        listener.BeginAcceptTcpClient(ClientConnected, listener);
      }
  
      public static void ClientConnected(IAsyncResult asyncResult)
      {
        var listener = (TcpListener)asyncResult.AsyncState;
        var client = listener.EndAcceptTcpClient(asyncResult);
        AcceptTcpClient(listener);
  
        DoAsync(client);
      }
    }
  </code></pre>
  
  <p>I think the best solution is the last (Example 3) but I'm not sure. What do you think of that?</p>