【发布时间】:2017-06-26 19:47:59
【问题描述】:
我有一个 BinaryReader 将多个字节读取到一个数组中。阅读器的底层流是 BufferedStream(其底层流是网络流)。我注意到有时reader.Read(arr, 0, len) 方法返回的结果与reader.ReadBytes(len) 不同(错误)。
基本上我的设置代码如下所示:
var httpClient = new HttpClient();
var reader = new BinaryReader(new BufferedStream(await httpClient.GetStreamAsync(url).ConfigureAwait(false)));
稍后,我正在从阅读器读取一个字节数组。我可以确认两种情况下的 sz 变量是相同的。
int sz = ReadSize(reader); //sz of the array to read
if (bytes == null || bytes.Length <= sz)
{
bytes = new byte[sz];
}
//reader.Read will return different results than reader.ReadBytes sometimes
//everything else is the same up until this point
//var tempBytes = reader.ReadBytes(sz); <- this will return right results
reader.Read(bytes, 0, sz); // <- this will not return the right results sometimes
看起来 reader.Read 方法比它需要的读入流的更远,因为在这种情况发生后,其余的解析将中断。显然我可以坚持使用 reader.ReadBytes,但我想在这里重用字节数组来轻松处理 GC。
会发生这种情况吗?是设置错误还是什么?
【问题讨论】:
-
可能与它是网络流有关?当您创建新的字节数组时,您“冻结”了流的一小部分,但是当您稍后将“冻结”的流与其余部分解析时,它将不匹配。注意:从未使用过网络流,完全是我的裤子:)
-
在什么条件下
ReadBytes可以读取比请求更少的字节?在哪种情况下Read可以读取比请求更少的字节?这种情况有何不同?
标签: c# binaryreader