1
FileStream stream = new FileStream("test",FileMode.Create);
BufferedStream buff = new BufferedStream(stream, 8);
BinaryWriter writer = new BinaryWriter(buff);
writer.Write(1);
writer.Write(2);
writer.Write(3);
Console.WriteLine(buff.Length);

据我了解,内容在此代码中达到 8 字节的缓冲区大小时会被刷新。那么为什么buff.Length返回 12 以及为什么只有当我显式调用时数据才会出现在文件中Dispose/Close

4

2 回答 2

1

工作正常 -它BufferedStream不会刷新:直到它关闭stream.Length8IE

// note these should really use "using" statements of similar
FileStream stream = new FileStream("test", FileMode.Create);
BufferedStream buff = new BufferedStream(stream, 8);
BinaryWriter writer = new BinaryWriter(buff);
writer.Write(1);
writer.Write(2);
writer.Write(3);
Console.WriteLine(stream.Length); // 8
Console.WriteLine(buff.Length); // 12

原因buff.Length12因为那是底层流的长度。基本上,BufferedStream只需重新暴露下面的流,并确保它不会错过缓冲数据,Flush()如果有缓冲数据,它会添加:

public override long Length
{
    get
    {
        this.EnsureNotClosed();
        if (this._writePos > 0)
        {
            this.FlushWrite();
        }
        return this._stream.Length;
    }
}

因此:

Console.WriteLine(stream.Length); // 8
Console.WriteLine(buff.Length); // 12
Console.WriteLine(stream.Length); // 12

请注意,FileStream也可以有自己的缓冲

于 2012-11-21T13:22:48.440 回答
0

会将其缓冲区的BufferedStream内容写入内部FileStream8字节。

但是,它FileStream本身有自己的缓冲,并且会不那么频繁地写入内容。

于 2012-11-21T13:18:51.070 回答