闽公网安备 35020302035485号
我发现 StreamReader 类既有 close() 还有 dispose() 方法,我想知道哪个方法更适合释放所有的资源?如果使用 using ,我知道它最终会调用 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);
}
}
}
2.当需要清理资源时,如果通过 using 方式调用的 Dispose() 方法,那肯定能保证资源被释放,如果你的对象需要用完即释放,也就是说希望在 using 语句结束之前被释放,那么这种情况可以手工调用 close() 方法,这两个方法他们是相互协作的,虽然它们看起来比较冗余。public class StreamReader : TextReader
{
protected override void Dispose(bool disposing)
{
if (_disposed)
{
return;
}
_disposed = true;
if (!_closable)
{
return;
}
try
{
if (disposing)
{
_stream.Close();
}
}
finally
{
_charPos = 0;
_charLen = 0;
base.Dispose(disposing);
}
}
public override void Close()
{
Dispose(disposing: true);
}
}
public abstract class TextReader : MarshalByRefObject, IDisposable
{
public void Dispose()
{
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
仔细观察代码,是不是发现 Dispose() 比 Close() 多了一个 GC.SuppressFinalize(this) 语句,这句代码是干嘛的呢?