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?
It depends.
If even one buffer of data is useful then you could call
Flushon every iteration, otherwise you might call it on every 5th. However, if partial data is useless then it makes sense not to callFlushat all.If memory is an issue then calling
Flushmore frequently would be a good thing.