C# 刷新 StreamWriter 和 MemoryStream

7

我使用以下代码片段,不确定是否需要调用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的flush方法根据API文档什么也不做,那这是怎么回事呢?我们为什么要调用一个什么也不做的方法?

2
你不必执行Flush(),因为你已经使用了"using": Writer/Reader会在Close/Dispose时自动关闭它们的缓冲区。如果你想加载/保存临时结果(比如流的一半)并继续处理流,则Flush()很有用。 - Dmitry Bychenko
3个回答

18
您不需要在StreamWriter上使用Flush,因为您正在处置它(通过将其放在using块中)。当它被处理时,它会自动刷新和关闭。
您不需要在MemoryStream上使用Flush,因为它没有缓冲写入到任何其他源的任何内容。根本没有任何东西需要在任何地方刷新。 Flush方法仅存在于MemoryStream对象中,因为它继承自Stream类。您可以在MemoryStream类的源代码中看到flush方法实际上什么也没做。

2

通常情况下,流会在写入数据时进行缓存(如果有相关设备,则定期将缓存刷新到相关设备上),因为向设备(通常是文件)写入数据的代价很高。MemoryStream 写入 RAM,因此缓存和刷新的整个概念都是多余的。数据已经始终在 RAM 中。

是的,释放流将导致其被刷新。


0

在注释中提到flush方法返回空的byte[],尽管我正在使用Using块。

     byte[] filecontent = null;
        using var ms = new MemoryStream();
        using var sw = new StreamWriter(fs);
        sw.WriteCSVLine(new[] { "A", "B" });//This is extension to write as CSV
        //tx.Flush();
        //fs.Flush();
        fs.Position = 0;
        filecontent = fs.ToArray();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接