C# flushing StreamWriter and a MemoryStream

无人久伴 提交于 2020-01-24 08:01:23

问题


I use the following snippet of code, and I'm unsure whether I need to call the Flush methods (once on StreamWriter, once on MemoryStream):

    //converts an xsd object to the corresponding xml string, using the UTF8 encoding
    public string Serialize(T t)
    {
        using (var memoryStream = new MemoryStream())
        {
            var encoding = new UTF8Encoding(false);

            using (var writer = new StreamWriter(memoryStream, encoding))
            {
                var serializer = new XmlSerializer(typeof (T));
                serializer.Serialize(writer, t);
                writer.Flush();
            }

            memoryStream.Flush();

            return encoding.GetString(memoryStream.ToArray());
        }
    }

First of all, because the code is inside the using block, I think the automatically called dispose method might do this for me. Is this true, or is flushing an entirely different concept?

According to stackoverflow itself:

Flush meaning clears all buffers for a stream and causes any buffered data to be written to the underlying device.

What does that mean in the context of the code above?

Secondly, the flush method of the MemoryStream does nothing according to the api, so what's up with that? why do we call a method that does nothing?


回答1:


You don't need to use Flush on the StreamWriter, as you are disposing it (by having it in a using block). When it's disposed, it's automatically flushed and closed.

You don't need to use Flush on the MemoryStream, as it's not buffering anything that is written to any other source. There is simply nothing to flush anywhere.

The Flush method is only present in the MemoryStream object because it inherits from the Stream class. You can see in the source code for the MemoryStream class that the flush method actually does nothing.




回答2:


In general Streams will buffer data as it's written (periodically flushing the buffer to the associated device if there is one) because writing to a device, usually a file, is expensive. A MemoryStream writes to RAM so the whole concept of buffering and flushing is redundant. The data is always in RAM already.

And yes, disposing the stream will cause it to be flushed.



来源:https://stackoverflow.com/questions/21230314/c-sharp-flushing-streamwriter-and-a-memorystream

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!