0

I need to read content from Stream in C#. I do not know which kind of Stream it would be. Let's assume it is Network Stream and network is very slow. So I can't read all bytes immediately. I know that 4 bytes in stream is integer and this int defines content length that we need to get from stream. How to do it without busy waiting (looping)?

private (int headerValue, bool isSuccess) ReadHeader()
{
    var bytesRead = 0;
    var headerBuffer = new byte[BufferHeaderLength];
    var headerIsReady = false;

    while (!headerIsReady)
    {
        try
        {
            var availableBytesToRead = Math.Min(BufferHeaderLength - bytesRead, underlyingStream.Length); // should be a number from 0 to 4

            bytesRead += underlyingStream.Read(headerBuffer, bytesRead, (int)availableBytesToRead);

            if (bytesRead == 0)
            {
                break;
            }
        }
        catch (Exception)
        {
            break;
        }

        headerIsReady = bytesRead == BufferHeaderLength;
    }

    var headerValue = headerIsReady ? BitConverter.ToInt32(headerBuffer, 0) : 0;

    return (headerValue, headerIsReady);
}
  • If you know it will be a network stream or similar, then it has facilities for this. If you dont know what type of stream it is, you will have to poll it for data. – TheGeneral Feb 19 '20 at 23:06
  • [ReadAsync](https://learn.microsoft.com/en-us/dotnet/api/system.io.stream.readasync?view=netframework-4.8) could be something to look into... but it will not remove need for looping (which not necessary the same as "busy-waiting") – Alexei Levenkov Feb 20 '20 at 01:14

0 Answers0