BinaryReader.Dispose(bool disposing)创建一个对stream的本地引用。为什么?

时间:2012-11-29 21:06:12

标签: c# reference stream garbage-collection

我在FCL代码中找到了一个不寻常的样本。

这是System.IO.BinaryReader:

中的方法
    protected virtual void Dispose(bool disposing) { 
        if (disposing) { 
            Stream copyOfStream = m_stream;
            m_stream = null; 
            if (copyOfStream != null && !m_leaveOpen)
                copyOfStream.Close();
        }
        m_stream = null; 
        m_buffer = null;
        m_decoder = null; 
        m_charBytes = null; 
        m_singleChar = null;
        m_charBuffer = null; 
    }

执行逻辑对'copyOfStream'有什么影响?

1 个答案:

答案 0 :(得分:9)

这样做是为了即使Stream.Close()抛出异常,m_stream也会设置为null。

回复评论

  

可以在Stream.Close()

上引发什么样的异常

关闭流时,刷新任何缓冲的输出,这会抛出异常,例如:由于网络故障。

  

我不确定这是理由。通常我们在使用块时调用Dispose,这意味着变量永远不会使用

在上面,如果抛出Stream.Close(),那么m_stream将已经为空。使用以下替代方法,如果Stream.Close()抛出:

,则m_stream将不会设置为null
m_stream.Close(); // <== throws
m_stream = null;  // <== not executed if Close() throws
  

但是在这种情况下如果我们谈论异常安全,有人可以重试对Dispose方法的调用并将面临NullReferenceException

它不会抛出NullReferenceException,因为它会测试null:

if (copyOfStream != null && !m_leaveOpen)
        copyOfStream.Close();