The function call MemoryStream.GetBuffer () is executed even after MemoryStream.Close (); What for?

In some open source code, I found the following construct:

var mstream = new MemoryStream();
// ... write some data to mstream
mstream.Close();
byte[] b = mstream.GetBuffer();

I thought this code would have “unexpected” behavior and could throw an exception, since the call Closeshould be an efficient call Disposeaccording to MSDN .

However, as far as I could tell from the experiment, the call GetBuffer()always succeeds and returns a valid result, even if I am Thread.Sleepwithin 20 seconds or forcibly removing garbage through GC.Collect().

If a call GetBuffer()is possible even after Close/ Dispose? In this case, why is the main buffer not available MemoryStream?

+4
source share
4 answers
  • This is not necessary. The buffer is memory-driven, so regular garbage collection will deal with it, without having to include it.
  • It is useful to be able to receive bytes of the memory stream even after the stream has been closed (which could happen automatically after the steam was passed to a method that writes something to the stream and then closes the specified stream), And for this to work , the object must be held in the buffer along with a record of how much was written on it.

ToArray() (, , , , GetBuffer() , ) , , , . , , , , . (, , ). , , (MemoryStream , MemoryStream , , , , ).

+3

MemoryStream. , , , . byte[]. , , buffer ( ) null, BCL - .

@mike , BCL GetBuffer ToArray , , , , ?. .

Dispose.

protected override void Dispose(bool disposing)
{
    try {
        if (disposing) {
            _isOpen = false;
            _writable = false;
            _expandable = false;
            // Don't set buffer to null - allow GetBuffer & ToArray to work.
    #if FEATURE_ASYNC_IO
                        _lastReadTask = null;
    #endif
        }
    }
    finally {
        // Call base.Close() to cleanup async IO resources
        base.Dispose(disposing);
    }
}

GetBuffer

public virtual byte[] GetBuffer()
{
    if (!this._exposable)
    {
        throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_MemStreamBuffer"));
    }
    return this._buffer;
}

Dispose _buffer , GetBuffer .

+4

GC , MemoryStream, , . , , , . , , GetBuffer:

public virtual byte[] GetBuffer()
{
    if (!this._exposable)
    {
        throw new UnauthorizedAccessException(Environment.GetResourceString("UnauthorizedAccess_MemStreamBuffer"));
    }
    return this._buffer;
}
+1

, IDisposable.Dispose . , , , , . - , , , Dispose .

, , , , ObjectDisposedException, - , , , , ObjectDisposedException, . , , , , , .

ObjectDisposedException , InvalidOperationException of IEnumerator<T>.MoveNext(): - ( Dispose, ) "", - . , , , , . , , (, a ConcurrentDictionary , ].

+1
source

Source: https://habr.com/ru/post/1542012/


All Articles