【问题标题】:C# flushing StreamWriter and a MemoryStreamC# 刷新 StreamWriter 和 MemoryStream
【发布时间】:2014-02-09 09:43:29
【问题描述】:

我使用以下 sn-p 代码,但我不确定是否需要调用 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 意思是清除流的所有缓冲区,并导致任何缓冲的数据写入底层设备。

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

其次是MemoryStreamdoes nothing according to the api的flush方法,那是怎么回事呢?为什么我们调用一个什么都不做的方法?

【问题讨论】:

  • 您不必执行 Flush(),因为您已经放置了“使用”:Writer/Reader 将在 Close/Dispose 时自动关闭其缓冲区。如果您想加载/保存时间结果(比如流的一半)并继续处理流,则 Flush() 很有用。

标签: c# flush


【解决方案1】:

评论刷新方法返回空字节[],虽然我正在使用 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();

【讨论】:

    【解决方案2】:

    您不需要在StreamWriter 上使用Flush,因为您正在处理它(通过将它放在using 块中)。当它被释放时,它会自动刷新并关闭。

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

    Flush 方法仅存在于 MemoryStream 对象中,因为它继承自 Stream 类。你可以在source code for the MemoryStream class 中看到flush 方法实际上什么都不做。

    【讨论】:

      【解决方案3】:

      一般而言,Streams 会在数据写入时缓冲数据(如果有,则定期将缓冲区刷新到关联设备),因为写入设备(通常是文件)的成本很高。 MemoryStream 写入 RAM,因此缓冲和刷新的整个概念是多余的。数据始终在 RAM 中。

      是的,释放流会导致它被刷新。

      【讨论】:

        猜你喜欢
        • 2010-11-27
        • 2011-08-04
        • 1970-01-01
        • 1970-01-01
        • 2013-05-07
        • 2016-02-13
        • 2011-08-05
        • 2012-08-14
        • 1970-01-01
        相关资源
        最近更新 更多