BinaryReader.Dispose(BOOL处置)创建一个本地引用流。为什么? [英] BinaryReader.Dispose(bool disposing) creates a local reference to stream. Why?

查看:169
本文介绍了BinaryReader.Dispose(BOOL处置)创建一个本地引用流。为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了整箱的代码不同寻常的样品



这是在System.IO.BinaryReader方式:

 受保护的虚拟无效的Dispose(BOOL处置){
如果(处置){
流copyOfStream = m_stream;
m_stream = NULL;
如果(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?


解决方案

它的完成使m_stream将被设置为null即使 Stream.Close()抛出异常。



在回应评论




什么样的​​异常可以在Stream.Close()


筹集

当您关闭流,任何缓冲输出刷新,它可以抛出一个异常,如:由于网络故障。




我不知道,这是一个理由。通常我们调用Dispose在使用块,这意味着变量都不会使用反正




在上面的,如果Stream.Close ()抛出,然后m_stream就已经为空。以下替换,m_stream不会,如果Stream.Close()抛出设置为空:

  m_stream.Close() ; //< ==抛出
m_stream = NULL; //<如果关闭()抛出
==不执行




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




它赢得了 ŧ抛出NullReferenceException异常,因为它会检测空:

 如果(!copyOfStream = NULL&放大器;&安培; m_leaveOpen)
copyOfStream.Close();


I found an unusual sample in FCL code.

This is method in 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; 
    }

What impact on the execution logic has 'copyOfStream'?

解决方案

It's done so that m_stream will be set to null even if Stream.Close() throws an exception.

In response to comments

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

When you close a stream, any buffered output is flushed, which can throw an exception, e.g. due to a network failure.

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

In the above, if Stream.Close() throws, then m_stream will already be null. With the following alternative, m_stream won't be set to null if Stream.Close() throws:

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

It won't throw a NullReferenceException because it tests for null:

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

这篇关于BinaryReader.Dispose(BOOL处置)创建一个本地引用流。为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆