编写测试以检查IDisposable
接口的dispose方法在调用后是否正确释放非托管资源的好方法是什么?
private bool disposed = false;
protected virtual void Dispose(bool disposing)
{
if (disposed)
return;
if (disposing)
{
// Free any other managed objects here.
}
// Free any unmanaged objects here
theUnmanagedResource.Dispose();
disposed = true;
}
我以为我可以检查处理后是否为假,但它并不能保证资源得到管理。
另一种方法是在theUnmanagedResource = null
之后设置theUnmanagedResources.Dispose()
并在测试用例之后检查它是否为空。但是从其他帖子中,他们将设置的资源设置为null,这不是好事:Setting Objects to Null/Nothing after use in .NET
答案 0 :(得分:0)
如上所述here,您可以检查是否直接调用 IDispose.Dispose (对象处理正确),然后 bool disposing 将在< em> virtual void Dispose(bool disposing):
using System;
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);
}
}