protected override void Dispose(bool disposing)
{
try
{
// We need to flush any buffered data if we are being closed/disposed.
// Also, we never close the handles for stdout & friends. So we can safely
// write any buffered data to those streams even during finalization, which
// is generally the right thing to do.
if (_stream != null)
{
// Note: flush on the underlying stream can throw (ex., low disk space)
if (disposing /* || (LeaveOpen && stream is __ConsoleStream) */)
{
CheckAsyncTaskInProgress();
Flush(true, true);
}
}
}
finally
{
// Dispose of our resources if this StreamWriter is closable.
// Note: Console.Out and other such non closable streamwriters should be left alone
if (!LeaveOpen && _stream != null)
{
try
{
// Attempt to close the stream even if there was an IO error from Flushing.
// Note that Stream.Close() can potentially throw here (may or may not be
// due to the same Flush error). In this case, we still need to ensure
// cleaning up internal resources, hence the finally block.
if (disposing)
{
_stream.Close();
}
}
finally
{
_stream = null;
_byteBuffer = null;
_charBuffer = null;
_encoding = null;
_encoder = null;
_charLen = 0;
base.Dispose(disposing);
}
}
}
}