title: Many TcpListener incoming connections
body: <p>I need to make a server that accepts <strong>and keeps for a long time</strong> many connections (perspectively over 100k).</p>
  
  <p>My code is below:</p>
  
  <pre><code>public delegate Task ClientConnectedEventHandler(Stream stream);
  
  public class Listener
  {
      public event ClientConnectedEventHandler OnClientConnected;
  
      private readonly TcpListener _tcpListener;
  
      public Listener()
      {
          _tcpListener = new TcpListener(new IPEndPoint(IPAddress.Any, 8082));
      }
  
      public void Start()
      {
          _tcpListener.Start();
          _tcpListener.BeginAcceptTcpClient(Accept, null);
      }
  
      private void Accept(IAsyncResult asyncResult)
      {
          _tcpListener.BeginAcceptTcpClient(Accept, null);
          var client = _tcpListener.EndAcceptTcpClient(asyncResult);
          var stream = client.GetStream();
          OnClientConnected?.Invoke(stream).ContinueWith(_ =&gt; client.Close());
      }
  }
  
  class Program
  {
      static void Main(string[] args)
      {
          var listener = new Listener();
          var count = 0;
          var infoLock = new object();
  
          listener.OnClientConnected += async stream =&gt;
          {
              lock (infoLock)
              {
                  count++;
                  Console.Title = count.ToString();
              }
              while (true)
              {
                  // Some logic
                  await Task.Delay(100);
              }
          };
  
          listener.Start();
          while (true)
          {
              Thread.Sleep(100);
          }
      }
  }
  </code></pre>
  
  <p>There is no problem when the logic takes up to 300-400 ms. But if I want to keep incoming connections for a long time, <strong>count</strong> variable increments very slow after accepting 8 clients, moreover appears a trouble with huge memory usage. What I'm doing wrong and how to resolve this?</p>