Reputation: 11138
I have a method that copies one stream into another. It's fairly simple and typical:
public static void CopyStream(Stream source, Stream destination)
{
byte[] buffer = new byte[32768];
int read;
while ((read = source.Read(buffer, 0, buffer.Length)) > 0)
{
destination.Write(buffer, 0, read);
}
}
When destination stream is a FileStream
, I observe that file is not created until copy is finished and destination stream is closed. I believe that calling destination.Flush()
from time to time while copying the stream would create the file and start writing contents to disk before copy is finished, which would release memory in my system.
When shall this destination.Flush()
call be done? Every iteration in my algorithm loop? Every N iterations? Never?
Upvotes: 3
Views: 915
Reputation: 137148
It depends.
If even one buffer of data is useful then you could call Flush
on every iteration, otherwise you might call it on every 5th. However, if partial data is useless then it makes sense not to call Flush
at all.
If memory is an issue then calling Flush
more frequently would be a good thing.
Upvotes: 1
Reputation: 14672
There is no hard and fast answer I don't think. Flush is provided so you have control over when the storage is effectively moved from memory to the stream. So the choice is yours, do it every loop iteration for minimal memory usage, do it less frequently for possibly higher performance at the expense of memory.
Upvotes: 1