Gigi
Gigi

Reputation: 29421

Stream Flush vs FlushAsync

Apart from the Flush() method, I noticed that the Stream class also has a FlushAsync() method. In what situations would you use the FlushAsync() method? Is flushing a buffer so expensive as to warrant running it asynchronously?

Upvotes: 6

Views: 7177

Answers (2)

Adriano Repetti
Adriano Repetti

Reputation: 67090

Yes, it can be very expensive because it may actually write data to underlying media.

Any of these conditions may be true:

  • You have a lot of data to write (according to buffer size).
  • Media itself may be pretty slow (network or a device with a slow interface).
  • There may be layers of abstractions in the middle that will do further processing before effective writing (a compression/encryption abstraction for example).

It can be expensive as much as any other writing operation then there is Async version (moreover it'll help API consistency).

How FlushAsync() is implemented is...an implementation detail, it may be a simple Task in thread pool or something more complex (asynchronous I/O may involve OS itself). It may even be synchronous (imagine to flush a MemoryStream, it has not any buffer).

Upvotes: 6

Steven Liekens
Steven Liekens

Reputation: 14088

From what I gather, calling stream.Write() may or may not put data in an intermediate in-memory buffer before being offloaded to its target destination. When this happens, stream.Write() unblocks before all of the data has actually been written.

The role of stream.Flush() would be to block the program until the intermediate buffer is clear. Depending on transfer speed and size of the data, you may want to Flush() asynchronously.

Upvotes: 2

Related Questions