spender
spender

Reputation: 120548

Double flush required?

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?
}

Upvotes: 6

Views: 955

Answers (2)

KeithS
KeithS

Reputation: 71601

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.

Upvotes: 4

Serge Belov
Serge Belov

Reputation: 5803

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

Upvotes: 4

Related Questions