title: Receiving byte stream using TCPClient consuming too much CPU
body: <p>I have a service which receives large byte streams from 3rd party systems using a <code>TcpListener</code>. Unfortunately, I don't have the option to change protocols or to something like <code>WCF</code>.</p>
  <p>When lots of systems are sending data at the same time, the CPU usage on my server spikes to nearly 90% and causes problems for other services. After taking a profile of my service, it looks like the CPU is being used reading the byte arrays from the <code>NetworkStream</code> into a <code>MemoryStream</code>. Here's an example of my server code</p>
  <pre><code>public void StartListening(CancellationToken token) {
      var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Any, port);
      listener.Start();
  
      while (!token.IsCancellationRequested) {
          var socket = listener.AcceptSocket();
          TcpClient tcpClient = new TcpClient(socket);
          var stream = tcpClient.GetStream();
  
          Task.Run(()=&gt; ReadStream(stream, token));
      }
  }
  
  private void ReadStream(NetworkStream stream, CancellationToken token){
      int offset = 0;
      int size = EXPECTED_FILE_SIZE;
      var inStream = new MemoryStream(size);
      while (size &gt; 0 &amp;&amp; !token.IsCancellationRequested) {
          try {
              int readin = stream.Read(inStream.GetBuffer(), offset, size);
              size -= readin;
              offset += readin;
          }
          catch (Exception ex) {
              Console.WriteLine(ex.Message);
              return;
          }    
      }
      //Do something with the memory stream
  }
  </code></pre>
  <p>I wrote a test client which sends multiple byte streams to the service at a time and every time the CPU spikes. I've tried a few things server side to fix the issue (including using <code>BeginRead</code> and <code>EndRead</code> on the network stream). The only thing that seems to help is when I send larger chunks of the byte streams from the client, but I have no control over the 3rd party systems which send the data.</p>
  <p>I have thought that it might work to accept all socket connections, but then limit the number of &quot;ReadStream&quot; tasks, but I don't know if there are any detrimental effects of accepting a socket and then not reading from it for a while.</p>