我得到了一个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。
会有什么原因导致这种情况发生吗?是设置错误还是有什么问题?
发布于 2017-06-27 03:57:48
在调用此函数之前,请确保清除了bytes
数组,因为Read(bytes, 0, len)
不会清除给定的字节数组,因此以前的一些字节可能会与新的字节冲突。很久以前,我的一个解析器也遇到了这个问题。只需将所有元素设置为零,或者确保您只读取(解析)给定的len
https://stackoverflow.com/questions/44767577
复制相似问题