我的方法如下
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
}
Run Code Online (Sandbox Code Playgroud)
我没有关闭StreamWriter,因为调用者应关闭内部流,这是否会导致内存泄漏?
为了好玩,我打开了反编译器来查看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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
有点罗嗦,但我认为这告诉我们的是,处理流会处理StreamWriter使用的唯一Disposable资源.该byteBuffer和charBuffer字段是数组,encoding而encoder不是一次性的,并且基本Dispose是虚拟的,所以流是会导致问题如果不清理的唯一的事情.
我想,这也清楚地表明,如果你想记录的数据流中的内容,并使其保持可用状态之后,那么你最挑衅都不能想处置您的StreamWriter的,因为这将处分流(关闭呼叫Dispose(true)).您还需要确保重置Stream的位置,因为您无疑会通过阅读内容来更改它.当然,这也意味着您可能想要检查CanSeekStream上的属性,并确保一旦您阅读了内容,您就可以将位置返回到之前的位置.
| 归档时间: |
|
| 查看次数: |
2012 次 |
| 最近记录: |