I
I
Illivion2012-11-29 21:52:18
.NET
Illivion, 2012-11-29 21:52:18

BinaryReader.Dispose(bool disposing) creates a local reference to the stream. What for?

Here is the method itself:

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; 
        }

m_stream - base stream
m_leaveOpen - set in the constructor if we want not to close the stream when the reader Dispose.
What is the meaning behind creating a stream reference (copyOfStream)? Why couldn't
m_stream.Close();
m_stream = null;
Is this due to the peculiarities of garbage collection?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
AM5800, 2012-11-30
@AM5800

I will assume that this is done to avoid NPE when calling stream.Close() if this code is called simultaneously from several threads. After all, if you write:
if (stream != null) stream.Close();
Then immediately after a successful check, stream can theoretically become null. When pre-copying to a local variable, this is excluded.

M
mayorovp, 2012-12-01
@mayorovp

This is done to avoid NullPointerException when calling Close simultaneously from different threads.
Under normal use, this situation is impossible, but the point of exceptions is precisely to catch abnormal use. This copy trick actually replaces the NullPointerException with a more appropriate ObjectDisposedException

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question