当 BinaryReader 打开时使用 Stream.Seek 是否安全?

Is it safe to use Stream.Seek when a BinaryReader is open?(当 BinaryReader 打开时使用 Stream.Seek 是否安全?)

本文介绍了当 BinaryReader 打开时使用 Stream.Seek 是否安全?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 BinaryReader 的底层缓冲策略,我不清楚读取存储在流中的偏移量是否可以,然后在此偏移量处重新定位流以恢复流式传输.

Because of the under the hood buffering strategy of BinaryReader, it is unclear to me whether is it ok or not to read an offset stored in a stream, then reposition the stream at this offset to resume the streaming.

举个例子,下面的代码是否可以:

As an example, is the following code ok:

using (var reader = new CustomBinaryReader(inputStream))
{
   var offset= reader.ReadInt32();
   reader.BaseStream.Seek(offset, SeekOrigin.Begin);

   //Then resume reading the streaming
}

或者我应该在寻找流之前关闭第一个二进制阅读器,然后重新打开第二个阅读器?

Or should I close the first binary reader before Seeking the stream and then reopen a second reader ?

int offset;
using (var firstReader = new CustomBinaryReader(inputStream))
{
   offset= firstReader.ReadInt32();
}
inputStream.Seek(offset, SeekOrigin.Begin);
using (var secondReader = new CustomBinaryReader(inputStream))
{
   //Then resume reading the streaming
}

推荐答案

BinaryReader 确实使用缓冲区,但从基本流中读取足够的字节以转换值.换句话说,ReadInt32() 将首先缓冲 4 个字节,ReadDecimal() 将首先缓冲 16 个字节,等等.ReadString() 是更棘手的方法,但它也有对策,一个字符串由 BinaryWriter 在文件中编码,它首先写入字符串长度.这样 BinaryReader 就知道在转换字符串之前要缓冲多少字节.

BinaryReader does use a buffer but only to read enough bytes from the base stream to convert a value. In other words, ReadInt32() will buffer 4 bytes first, ReadDecimal() will buffer 16 bytes first, etcetera. ReadString() is the trickier method but it has counter-measures as well, a string is encoded in the file by BinaryWriter which writes the string length first. So that BinaryReader knows exactly how many bytes to buffer before converting the string.

因此在 ReadXxx() 方法之一返回后缓冲区始终为空,并且在 BaseStream 上调用 Seek() 没问题.也是微软不需要重写 Seek() 方法的原因.

So the buffer is always empty after one of the ReadXxx() method returns and calling Seek() on the BaseStream is fine. Also the reason that Microsoft didn't need to override the Seek() method.

MSDN 文章中的警告是恰当的,如果您在 Seek() 调用之后调用 ReadXxx() 方法,您肯定会多次阅读该偏移"值.然而,我认为这完全是故意的.

The cautionary note in the MSDN article is appropriate, you certainly will read that "offset" value more than once if you call a ReadXxx() method after the Seek() call. I however assume that was entirely intentional.

这篇关于当 BinaryReader 打开时使用 Stream.Seek 是否安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:当 BinaryReader 打开时使用 Stream.Seek 是否安全?

基础教程推荐