当我显式关闭 Stream 时,关闭 StreamReader(或 StreamWriter)是否有好处?

Is there a benefit in closing StreamReader (or StreamWriter) when I close Stream explicitly?

我有以下代码。在这里,我将 StreamReader 构造函数与 leaveOpen: true 一起使用,为此我需要提供先前的参数 。这很麻烦。由于我将 streamusing 结合使用,因此将 StreamReaderusing 结合使用对我有什么好处吗?如果改为 StreamWriter,答案会改变吗?

using (Strem stream = ...)
{
    ...
    using (StreamReader sr = new StreamReader(stream, Encoding.UTF8, true, 1024, true))
    {
        ...
    }
    ...
}

如果改用下面的代码,我会失去什么?

using (Strem stream = ...)
{
    ...
    StreamReader sr = new StreamReader(stream);

    ...

    ...
}

您确实需要关闭 StreamWriter(通常通过 using 块),否则其缓冲区中的数据可能会丢失。

因为StreamReaderStreamWriter都默认自动关闭流,如果你想从你的代码中删除一个using块,它应该是Stream您从 using.

中删除的

如果你不能那样做,例如你从别处借用了 Stream 而不想你关闭它,那么你必须使用 leaveOpen 参数你'你已经知道了。您不能只省略 StreamReader/StreamWriterusing 语句以使其保持打开状态的原因是垃圾收集器仍会触发一些清理(尽管不像很多)因为对象无法访问...现在只有这会在不相关的时间发生,从而产生一个很难发现的不可预测的错误。

如果不显式控制缓冲区大小等就不能指定 leaveOpen 确实很难看。我可以建议一个类似于 StreamReader CreateStreamReaderLeaveOpen(Stream) 的辅助方法吗?

因为您在处理 StreamReader does nothing execpt call the the Dispose method of the TextReader class 的构造函数中将 leaveOpen 设置为 true,它本身什么都不做。

protected override void Dispose(bool disposing)
{
    // Dispose of our resources if this StreamReader is closable.
    // Note that Console.In should be left open.
    try {
        // Note that Stream.Close() can potentially throw here. So we need to 
        // ensure cleaning up internal resources, inside the finally block.  
        if (!LeaveOpen && disposing && (stream != null))
            stream.Close();
    }
    finally {
        if (!LeaveOpen && (stream != null)) {
            stream = null;
            encoding = null;
            decoder = null;
            byteBuffer = null;
            charBuffer = null;
            charPos = 0;
            charLen = 0;
            base.Dispose(disposing);
        }
    }
}

使用 StreamWriter 它确实发生了一些变化,因为 it will not flush it's internal buffers to the underlying stream unless you dispose of the writer