2012-11-21 80 views
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字節的bufer大小時,內容被刷新。 那麼爲什麼buff.Length返回12,以及爲什麼數據只出現在文件中,如果我明確呼籲Dispose/Closec#BufferedSize無法正常工作?

+0

這裏是什麼? –

+0

它應該是buff,sry – asdas

回答

1

BufferedStream工作正常 - 它不刷新:stream.Length8直到它關閉;即

// 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也可以有自己的緩衝區

0

BufferedStream將在8字節之後將其緩衝區的內容寫入內部FileStream

然而,FileStream本身有自己的緩衝區,並且會少寫內容。