Read from C# Stream without busy waiting

266 views Asked by At

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);
}
0

There are 0 answers