title: TcpListener: how to stop listening while awaiting AcceptTcpClientAsync()?
body: <p>I don't know how to properly close a TcpListener while an async method await for incoming connections.
  I found this code on SO, here the code :</p>
  
  <pre><code>public class Server
  {
      private TcpListener _Server;
      private bool _Active;
  
      public Server()
      {
          _Server = new TcpListener(IPAddress.Any, 5555);
      }
  
      public async void StartListening()
      {
          _Active = true;
          _Server.Start();
          await AcceptConnections();
      }
  
      public void StopListening()
      {
          _Active = false;
          _Server.Stop();
      }
  
      private async Task AcceptConnections()
      {
          while (_Active)
          {
              var client = await _Server.AcceptTcpClientAsync();
              DoStuffWithClient(client);
          }
      }
  
      private void DoStuffWithClient(TcpClient client)
      {
          // ...
      }
  
  }
  </code></pre>
  
  <p>And the Main :</p>
  
  <pre><code>    static void Main(string[] args)
      {
          var server = new Server();
          server.StartListening();
  
          Thread.Sleep(5000);
  
          server.StopListening();
          Console.Read();
      }
  </code></pre>
  
  <p>An exception is throwed on this line </p>
  
  <pre><code>        await AcceptConnections();
  </code></pre>
  
  <p>when I call Server.StopListening(), the object is deleted.</p>
  
  <p>So my question is, how can I cancel AcceptTcpClientAsync() for closing TcpListener properly.</p>