我有如下方法
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
}
我没有关闭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);
}
}
}
}
有点罗word,但是我认为这告诉我们的是,处理流只处理StreamWriter使用的唯一Disposable资源. byteBuffer和charBuffer字段是数组,编码和编码器不是一次性的,而基本Dispose是虚拟的,因此,如果不对其进行清理,则Stream是唯一会引起问题的东西.
我认为这也很清楚,如果您要记录流的内容并在之后将其保持可用状态,那么您绝对会不想处置您的StreamWriter,因为这将处置Stream(Close调用)处理(true)).您还需要确保重设Stream的位置,因为毫无疑问,您将通过阅读内容来更改它的位置.当然,这也意味着您可能希望检查Stream上的CanSeek属性,并确保一旦阅读内容,便能够将位置恢复到之前的位置.
标签:stream,dispose,c 来源: https://codeday.me/bug/20191208/2090756.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。