-2

A FileStream buffers the bytes it needs to write. If the buffer is full, all bytes are written (flushed) to the file. This write process might take some time.

As every byte being added to the FileStream might cause a Flush, the write functions have an async version. It is possible to write to the stream without waiting for the write to be finished.

Class StreamWriter makes it easier to write text to the FileStream. Writing data to the StreamWriter causes data being written to the underlying stream, and thus might cause a Flush.

This makes functions like StreamWriter.Write(int) potentially slow. However, there are no async versions of these functions, except to write chars or strings. There is even an async version to WriteLine.

Are such functions not needed when I write fairly small objects like integers and doubles?

Harald Coppoolse
  • 28,834
  • 7
  • 67
  • 116
  • 2
    If you look at the documentation, you'll see that most of those methods just turn immediately around and call `ToString()` on the value that's been passed in. It's difficult to see what benefit they provide other than slightly less typing (bear in mind that this type dates from the .NET stone age, so the thinking may have been different then). – Damien_The_Unbeliever Jan 24 '18 at 10:59
  • Stream are automatically flush using a timer. So it always does a flush (not might cause flush). unless you turn automatic flushing off. If you do not want the timers running turn off flush and then make sure you manually flush before closing the file so all the data gets written to the file. – jdweng Jan 24 '18 at 11:19
  • 1
    `TextWriter.Write(int)` must have looked like a good idea in .NET 1.1 but do you really want to use it in 2018? Stopping that would resolve this question and a few others. – H H Jan 24 '18 at 12:06

1 Answers1

0

It seems to me that it depends more on application specifics, a StreamWriter instance buffer size, server hardware, server configuration and expected load profile rather than small size of data that is being written. You can create two versions of application (one with StreamWriter.Write(string) and another with StreamWriter.WriteAsync(string), which TextWriter.Write(int) eventually invokes) and test how this implementation detail affects throughput, memory usage etc.

For more information check Should I expose asynchronous wrappers for synchronous methods? article by Stephen Toub and StreamWriter() constructor with bufferSize parameter page on MSDN.

Leonid Vasilev
  • 11,910
  • 4
  • 36
  • 50