简体   繁体   中英

Do you have to flush your BinaryWriter data

In C# I am using BinaryWriter like this:

BinaryWriter br = new BinaryWriter(myPipe);
var bytes = new byte[5];
br.Write(bytes);
br.Flush();

https://msdn.microsoft.com/de-de/library/system.io.binarywriter.flush(v=vs.110).aspx mentions you should use flush your binary writer.

However I noticed that the data already gets send as soon as br.Write is called and I see no need to call br.Flush?

I am wondering if I can remove that 1 (unnecessary) line of code: br.Flush() or if there is more to it?

That entirely depends on the stream that is used . Flushing a stream means that any buffered data which has not been written yet will be written during the flush. So if the stream you use does not buffer any data, you will not see any difference. If you do not flush the stream it will get flushed the moment you close it.

The documentation you mentionted only states that:

All derived classes should override Flush to ensure that all buffered data is sent to the stream.

Flushing the stream will not flush its underlying encoder unless you explicitly call Flush or Close. Setting AutoFlush to true means that data will be flushed from the buffer to the stream, but the encoder state will not be flushed. This allows the encoder to keep its state (partial characters) so that it can encode the next block of characters correctly. This scenario affects UTF8 and UTF7 where certain characters can only be encoded after the encoder receives the adjacent character or characters .

Calling Flush() with BinaryWriter simply flushes the underlying stream ( BaseStream ).

This is normally done automatically when the underlying stream is closed, so in most cases you do not need to call it explicitly, and if you are writing multiple records using BinaryWriter, and the underlying stream is a FileStream, it will be much more efficient not to call it each time.

You also do not need to call Flush ( for BinaryWriter ) before calling Seek, when writing multiple records to different locations.

For other stream writing classes which do buffer data the situation may be different.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM