Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Infinite Do...while loop using Async Await

Tags:

c#

async-await

I have following code:

public static async Task<string> 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 && bytesRead> 0);

   byteArray = ms.ToArray();
   return encoding.GetString(ms.ToArray());
}

I am trying to read Stream to write into MemoryStream asynchronously, but the Do...while loop is failing to break. I mean it's an infinite loop. How to solve this?

like image 787
Bhushan Firake Avatar asked Jun 03 '13 17:06

Bhushan Firake


1 Answers

First, in an exceptional situation, your loop would continue indefinitely. You shouldn't catch and ignore exceptions.

Secondly, if the stream doesn't actually end, then bytesRead would never be zero. I suspect this is the case because the name of the method (ReadLineAsync) doesn't imply to me that it will read until the end of the stream.

P.S. CanRead does not ever change for a specific stream. It's whether it makes semantic sense for a stream to do a read operation, not whether it can read right now.

like image 189
Stephen Cleary Avatar answered Sep 20 '22 10:09

Stephen Cleary