Skip to content

Instantly share code, notes, and snippets.

@cstlaurent
Created September 5, 2014 02:43
Show Gist options
  • Save cstlaurent/4347e31deab132a813af to your computer and use it in GitHub Desktop.
Save cstlaurent/4347e31deab132a813af to your computer and use it in GitHub Desktop.
/// <summary>
/// Closes the current StreamWriter object and the underlying stream.
/// </summary>
/// <exception cref="T:System.Text.EncoderFallbackException">The current encoding does not support displaying half of a Unicode surrogate pair.</exception><filterpriority>1</filterpriority>
public override void Close()
{
this.Dispose(true);
GC.SuppressFinalize((object) this);
}
/// <summary>
/// Releases the unmanaged resources used by the <see cref="T:System.IO.StreamWriter"/> and optionally releases the managed resources.
/// </summary>
/// <param name="disposing">true to release both managed and unmanaged resources; false to release only unmanaged resources. </param><exception cref="T:System.Text.EncoderFallbackException">The current encoding does not support displaying half of a Unicode surrogate pair.</exception>
[__DynamicallyInvokable]
protected override void Dispose(bool disposing)
{
try
{
if (this.stream == null || !disposing && (!this.LeaveOpen || !(this.stream is __ConsoleStream)))
return;
this.CheckAsyncTaskInProgress();
this.Flush(true, true);
if (this.mdaHelper == null)
return;
GC.SuppressFinalize((object) this.mdaHelper);
}
finally
{
if (!this.LeaveOpen)
{
if (this.stream != null)
{
try
{
if (disposing)
this.stream.Close();
}
finally
{
this.stream = (Stream) null;
this.byteBuffer = (byte[]) null;
this.charBuffer = (char[]) null;
this.encoding = (Encoding) null;
this.encoder = (Encoder) null;
this.charLen = 0;
base.Dispose(disposing);
}
}
}
}
}
@czmoss
Copy link

czmoss commented Sep 5, 2014

I hope you don't mind the unsolicited comment. I saw your comment on http://blog.pluralsight.com/how-to-use-idisposable-in-net and, as I have been interested in this “disposal” problem, I looked into this example.

StreamWriter is-a TextWriter.
The 0-parameter TextWriter.Dispose() (what is called when using StreamWriter in a using block) is, according to http://referencesource.microsoft.com/mscorlib/system/io/textwriter.cs.html#2e39b8daeeed8db5,

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

So one may as well write

            using (var writer = new StreamWriter(...))
            {
                ...
            }

instead of

            var writer = new StreamWriter(...);
            ...
            writer.Close();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment