Can “not recycle StreamWriter” cause memoryLeak in this case?

I have a method that follows

public int TranslateOOV(string word, Stream logStream)
{
StreamWriter writer = new StreamWriter(logStream);

//Do some logging
//dont close the writer and leave the caller close the stream
}

I do not close StreamWriter, since the caller must close the internal stream, does this cause memoryleak?

+3
source share
4 answers

Just for fun, I hacked the decompiler to see what Dispose does on StreamWriter (thinking that the underlying stream is the only resource that needs to be disposed of). Here's what happened:

protected override void Dispose(bool disposing)
{
    try
    {
        if (this.stream != null)
        {
            if (disposing || (this.Closable || this.stream as __ConsoleStream))
            {
                this.Flush(true, true);
                if (this.mdaHelper != null)
                {
                    GC.SuppressFinalize(this.mdaHelper);
                }
            }
        }
    }
    finally
    {
        if (this.Closable)
        {
            if (this.stream != null)
            {
                if (disposing)
                {
                    this.stream.Close();
                }
                this.stream = null;
                this.byteBuffer = null;
                this.charBuffer = null;
                this.encoding = null;
                this.encoder = null;
                this.charLen = 0;
                base.Dispose(disposing);
            }
        }
    }
}

, , , , StreamWriter. byteBuffer charBuffer , encoding encoder , Dispose , Stream - , , .

, , , StreamWriter, Stream (Close calls Dispose(true)). , reset Stream, , , , . , , , , CanSeek , , , , .

+5

, , . , .

0

, , , , IDisposable.
, , , .
, , .

0

, , StreamWriter Using(), Streamwriter . , , .

: Microsoft. StreamWriter , @ckramer, Close . http://msdn.microsoft.com/en-us/library/system.io.stream.close.aspx

Dispose, true, . Close. , Stream .

, Microsoft . .

Close, Dispose.

That doesn't make any sense. Thus, they not only ignore their first statements, but also create a class that violates the Open-Closed principle, which allows you to modify the class in ways that can lead to unexpected scenarios. For such a statement, Close must be completely non-virtual, or they should have corrected any considerations adopted in this consideration.

-2
source

All Articles