title: Replacing Socket.ReceiveAsync with NetworkStream.ReadAsync (awaitable)
body: <p>I have an application that makes a couple hundred TCP connections at the same time, and receives a constant stream of data from them.</p>
  
  <pre><code> private void startReceive()
      {
          SocketAsyncEventArgs e = new SocketAsyncEventArgs();
          e.Completed += receiveCompleted;
          e.SetBuffer(new byte[1024], 0, 1024);
          if (!Socket.ReceiveAsync(e)) { receiveCompleted(this, e); }  
      }
  
      void receiveCompleted(object sender, SocketAsyncEventArgs e)
      {
          ProcessData(e);
  
          if (!Socket.ReceiveAsync(e)) { receiveCompleted(this, e); }
      }
  </code></pre>
  
  <p>My attempts led to something like this:</p>
  
  <pre><code>private async void StartReceive()
      {
          byte[] Buff = new byte[1024];
          int recv = 0;
          while (Socket.Connected)
          {
              recv = await NetworkStream.ReadAsync(Buff, 0, 1024);
              ProcessData(Buff,recv);
          }
      }
  </code></pre>
  
  <p>The issue I had was the method calling <code>StartReceive()</code> would block, and not get to the accompanying <code>StartSend() method called after</code>StartReceive()<code>. Creating a new task for</code>StartReceive()<code>would just end up with 300-ish threads, and it seems to do so just by calling</code>StartReceive()` anyways.</p>
  
  <p>What would be the correct method of implementing the new <code>async</code> and <code>await</code> keywords on my existing code while using a <code>NetworkStream</code> so it is using the thread pool that <code>Socket.SendAsync()</code> and <code>Socket.ReceiveAsync()</code> are using to avoid having to have hundreds of threads/tasks?</p>
  
  <p>Is there any performance advantage of using <code>networkstream</code> in this manner over i/o completion ports with <code>beginreceive</code>?</p>