我的类包含一个来自 Interop 的对象,并在其上调用一个方法,使其分配内容。它还公开了一个释放这些东西的方法,所以我希望我应该在 Dispose() 中调用它:
class MyClass : IDisposable
{
private DllName.ComClassName comInstance;
void SomeMethod()
{
comInstance = new DllName.ComClassName();
comInstance.AllocStuff();
}
public void Dispose()
{
comInstance.FreeThatStuff();
}
}
现在,我应该展开所有内容以遵循 Dispose 模式。我没有其他可以释放的一次性或非托管资源,因此假设 comInstance 是托管的(这不是 Interop 所做的,将非托管包装到托管中吗?),我认为该模式分解为:
public void Dispose()
{
if (comInstance != null)
{
comInstance.FreeStuff();
comInstance = null;
}
}
除非我在 MyClass 的实例上显式调用 Dispose() 否则会导致泄漏,这会使 Dispose 模式有缺陷?那么这是否意味着 comInstance 必须是非托管的,并且该模式分解为:
public void Dispose()
{
DisposeComInstance();
GC.SuppressFinalize(this);
}
~MyClass()
{
DisposeComInstance();
}
private void DisposeComInstance()
{
if (comInstance != null)
{
comInstance.FreeStuff();
comInstance = null;
}
}
编辑:
- 为了避免完整模式使我的类(class)困惑,我可以只密封我的类(class)吗?
- 我怎么知道 ComClassName(以及通常的任何类)是非托管的?
最佳答案
最终你想要这种模式:
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~MyClass()
{
Dispose(false);
}
private void Dispose(bool disposing)
{
if (disposing)
{
// Dispose of disposable objects here
}
// Other unmanaged cleanup here which will be called by the finalizer
if (comInstance != null)
{
comInstance.FreeStuff();
comInstance = null;
}
// Call base dispose if inheriting from IDisposable class.
base.Dispose(true);
}
有关原因的精彩文章,请查看 Implementing IDisposable and the Dispose pattern properly.
关于c# - 包装 Interop COM 对象时如何在 c# 中实现处置模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1196203/