gpt4 book ai didi

c# - BinaryReader.Dispose(bool disposing) 创建流的本地引用。为什么?

转载 作者:太空狗 更新时间:2023-10-29 22:33:13 25 4
gpt4 key购买 nike

我在 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”对执行逻辑有什么影响?

最佳答案

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

回应评论

what kind of exception can be raised on Stream.Close()

当你关闭一个流时,任何缓冲的输出都会被刷新,这可能会抛出异常,例如由于网络故障。

I'm not sure that this is a rationale. Usually we're calling Dispose in using block, and this means that variable will never used anyway

在上面,如果 Stream.Close() 抛出异常,则 m_stream 已经为空。使用以下替代方案,如果 Stream.Close() 抛出,则 m_stream 不会设置为 null:

m_stream.Close(); // <== throws
m_stream = null; // <== not executed if Close() throws

But in this case if we're talking about exception-safety, someone can retry call to Dispose method and will face NullReferenceException

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

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

关于c# - BinaryReader.Dispose(bool disposing) 创建流的本地引用。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13634722/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com