title: Infinite Do...while loop using Async Await
body: <p>I have following code:</p>
  
  <pre><code>public static async Task&lt;string&gt; ReadLineAsync(this Stream stream, Encoding encoding)
  {
  byte[] byteArray = null;
  using (MemoryStream ms = new MemoryStream())
  {
     int bytesRead= 0;
     do
     {
         byte[] buf = new byte[1024];
         try
         {
               bytesRead = await stream.ReadAsync(buf, 0, 1024);
               await ms.WriteAsync(buf, 0, bytesRead);
         }
         catch (Exception e)
         {
               Console.WriteLine(e.Message + e.StackTrace);
         }
     } while (stream.CanRead &amp;&amp; bytesRead&gt; 0);
  
     byteArray = ms.ToArray();
     return encoding.GetString(ms.ToArray());
  }
  </code></pre>
  
  <p>I am trying to read <code>Stream</code> to write into <code>MemoryStream</code> asynchronously, but the <code>Do...while</code> loop is failing to break. I mean it's an infinite loop. How to solve this?</p>