StreamReader类同时具有close和dispose方法。我想知道该调用哪个方法来清理所有资源。
如果使用using block,我想它会调用dispose方法。清理所有资源就足够了吗?
发布于 2010-11-11 18:50:58
using块将在StreamReader实例上调用Dispose()。一般来说,如果一个类型是IDisposable,你应该把它放在using作用域中。
编辑:如果您使用Reflector查看StreamReader的Close()实现,您将看到它正在调用Dispose(true)。因此,如果您没有使用using作用域,那么在这个特定的例子中,手动调用Close()与调用Dispose()是相同的。
protected override void Dispose(bool disposing)
{
try
{
if ((this.Closable && disposing) && (this.stream != null))
{
this.stream.Close();
}
}
finally
{
if (this.Closable && (this.stream != null))
{
this.stream = null;
this.encoding = null;
this.decoder = null;
this.byteBuffer = null;
this.charBuffer = null;
this.charPos = 0;
this.charLen = 0;
base.Dispose(disposing);
}
}
}发布于 2015-05-25 23:13:55
我们都知道System.IO.StreamReader不是唯一一个实现IDisposable和Close()方法的.NET 4.0+类。对于这个问题中的StreamReader,源代码显示基类TextReader.Close()和TextReader.Dispose()都运行相同的代码行。您还可以在代码中看到,在调用StreamReader.Dispose()时,TextReader.Dispose()是其实现(因为StreamReader不会覆盖Dispose的方法重载签名)。
因此,对StreamReader.Dispose()的调用将运行this inherited line of code,它将调用受保护的覆盖方法StreamReader.Dispose(disposing: true),StreamReader.Close()也将调用StreamReader.Dispose(disposing: true)。因此,对于StreamReader,Close()和Dispose()恰好运行相同的代码行。
对于Close()或Dispose()的问题,更一般的、非特定于类的回答可能是注意到微软有相当清晰的documentation on implementing IDisposable and the Dispose pattern。快速阅读就足以说明实现Close()方法不是Dispose模式的要求。
我之所以在这么多实现IDisposable的类上找到Close()方法,是约定的结果,而不是要求。
有人评论说
使用Dispose模式实现IDisposable并具有Close()方法的另一个类的示例。在这种情况下,Close()是否运行与Dispose()相同的代码?我没有看过源代码,但我会说不一定。
发布于 2010-11-11 22:31:51
通过using块使用Dispose来保证发生清理。
如果您在using块结束之前完成了对象操作,请使用Close,以便尽可能及时地释放任何资源。
因此,两者将携手工作,尽管如果您无论如何都要在几纳秒内到达块的末尾,则后者可能是多余的。
https://stackoverflow.com/questions/4153595
复制相似问题