Reputation: 29421
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
Reputation: 67090
Yes, it can be very expensive because it may actually write data to underlying media.
Any of these conditions may be true:
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
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