C#刷新StreamWriter和MemoryStream

问题描述 投票:4回答:3

我使用以下代码段,并且不确定是否需要调用Flush方法(在StreamWriter上一次,在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());
        }
    }

首先,因为代码在using块中,所以我认为自动调用的dispose方法可能会对我有用。这是真的,还是冲洗是一个完全不同的概念?

根据stackoverflow本身:

Flush的含义是清除流的所有缓冲区,并使所有缓冲的数据写入底层设备。

在上面的代码中这是什么意思?

第二,MemoryStream does nothing according to the api的冲洗方法,那是怎么回事?为什么我们调用什么都不做的方法?

c# flush
3个回答
10
投票

[您不需要在Flush上使用StreamWriter,因为您正在处理它(将其放在using块中)。处置后,会自动冲洗并关闭。

您不需要在Flush上使用MemoryStream,因为它不会缓冲写入任何其他源的任何内容。根本没有要冲洗的地方。

Flush方法仅在MemoryStream对象中存在,因为它继承自Stream类。您可以在source code for the MemoryStream class中看到MemoryStream方法实际上不执行任何操作。


2
投票

通常,Streams将在写入数据时对数据进行缓冲(如果有的话,会定期将缓冲区刷新到关联的设备),因为写入设备(通常是文件)的开销很大。 MemoryStream写入RAM,因此缓冲和刷新的整个概念都是多余的。数据始终已经在RAM中。

是的,处理流将导致其被冲洗。


0
投票

注释刷新方法返回空字节[],尽管我正在使用using块

flush
© www.soinside.com 2019 - 2024. All rights reserved.