110,536
社区成员
发帖
与我相关
我的任务
分享
class BaseClass : IDisposable
{
// Flag: Has Dispose already been called?
bool disposed = false;
// Public implementation of Dispose pattern callable by consumers.
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
// Protected implementation of Dispose pattern.
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing) {
// Free any other managed objects here.
//
}
// Free any unmanaged objects here.
//
disposed = true;
}
~BaseClass()
{
Dispose(false);
}
}
以上例子中的每一个点都很重要,资源释放这块微软设计的很严谨的!为何要调用 GC.SuppressFinalize(this)?为何析构中的Dispose的参数是false?我想楼主看明白后就知道你错在哪了,也就明白这不是语言的bug,而是你代码写的不对,官方有清晰的文档告诉你应该怎么写,你偏不这么写,出了问题还赖人家?