我需要从 C# 中的 Stream 读取内容。我不知道它会是哪种流。让我们假设它是网络流并且网络非常慢。所以我不能立即读取所有字节。我知道流中的 4 个字节是整数,这个 int 定义了我们需要从流中获取的内容长度。如何在不忙于等待(循环)的情况下做到这一点?
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);
}