只是为了好玩,我打开反编译器,看看Dispose在StreamWriter上做了些什么(或许底层流是需要处理的唯一资源)。这里是出来了:
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的,因为这将处理流(Close calls Dispose(true)
)。您还希望确保重置流的位置,因为您无疑会通过阅读内容来更改它的位置。当然,这也意味着你可能想检查Stream上的CanSeek
属性,并确保一旦你阅读了内容,你将能够返回到之前的位置。
我很担心泄漏,设计提供了你准确的说法 – 2011-06-01 11:17:25