title: async / await vs BeginRead, EndRead
body: <p>I don't quite 'get' async and await yet, and I'm looking for some clarification around a particular problem I'm about to solve. Basically, I need to write some code that'll handle a TCP connection. It'll essentially just receive data and process it until the connection is closed. </p>
  
  <p>I'd normally write this code using the NetworkStream BeginRead and EndRead pattern, but since the async / await pattern is much cleaner, I'm tempted to use that instead. However, since I admittedly don't fully understand exactly what is involved in these, I'm a little wary of the consequences. Will one use more resources than the other; will one use a thread where another would use IOCP, etc. </p>
  
  <p>Convoluted example time. These two do the same thing - count the bytes in a stream:</p>
  
  <pre><code>class StreamCount
  {
      private Stream str;
      private int total = 0;
      private byte[] buffer = new byte[1000];
  
      public Task&lt;int&gt; CountBytes(Stream str)
      {
          this.str = str;
  
          var tcs = new TaskCompletionSource&lt;int&gt;();
          Action onComplete = () =&gt; tcs.SetResult(total);
          str.BeginRead(this.buffer, 0, 1000, this.BeginReadCallback, onComplete);
  
          return tcs.Task;
      }
  
      private void BeginReadCallback(IAsyncResult ar)
      {
          var bytesRead = str.EndRead(ar);
          if (bytesRead == 0)
          {
              ((Action)ar.AsyncState)();
          }
          else
          {
              total += bytesRead;
              str.BeginRead(this.buffer, 0, 1000, this.BeginReadCallback, ar.AsyncState);
          }
      }
  }
  </code></pre>
  
  <p>... And...</p>
  
  <pre><code>    public static async Task&lt;int&gt; CountBytes(Stream str)
      {
          var buffer = new byte[1000];
          var total = 0;
          while (true)
          {
              int bytesRead = await str.ReadAsync(buffer, 0, 1000);
              if (bytesRead == 0)
              {
                  break;
              }
              total += bytesRead;
          }
          return total;
      }
  </code></pre>
  
  <p>To my eyes, the async way looks cleaner, but there is that 'while (true)' loop that my uneducated brain tells me is going to use an extra thread, more resources, and therefore won't scale as well as the other one. But I'm fairly sure that is wrong. Are these doing the same thing in the same way?</p>