3

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?

4

2 に答える 2

1

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.

于 2012-10-19T09:17:30.937 に答える
1

It depends.

  • How robust do you want the copy to be?
  • How useful is partial data?

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.

于 2012-10-19T09:19:06.317 に答える