6

Is it necessary to flush a Stream after flushing a StreamWriter?

public static async Task WriteStringAsync(this Stream stream, string messageString)
{
        var encoding = new UTF8Encoding(false); //no BOM
        using (var streamWriter = new StreamWriter(stream, encoding))
        {
            await streamWriter.WriteAsync(messageString);
            await streamWriter.FlushAsync();
        }
        await stream.FlushAsync(); //is this necessary?
}
spender
  • 117,338
  • 33
  • 229
  • 351

2 Answers2

4

It's not necessary, the StreamWriter.Flush and StreamWriter.FlushAsync methods call the Stream.Flush internally.

Serge Belov
  • 5,633
  • 1
  • 31
  • 40
4

According to the MSDN docs, this could be forgiven as "just making sure"...

StreamWriter.Flush():

Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.

Stream.Flush():

When overridden in a derived class, clears all buffers for this stream and causes any buffered data to be written to the underlying device.

... However, a closer look at the code in TypeDescriptor shows that StreamWriter.Flush() (and I would assume its asynchronous counterpart FlushAsync) is an overload that calls the primary function, passing two Boolean parameters which instruct the StreamWriter to flush the Stream and the Unicode encoder as well. So, one call to StreamWriter.FlushAsync(), coupled with the await keyword to ensure the async operation has happened completely, should be fine.

KeithS
  • 70,210
  • 21
  • 112
  • 164