【发布时间】:2015-05-29 05:43:44
【问题描述】:
我有一个 COM 对象:
_myObject = (IMyInterface)Activator.CreateInstance(...);
我可以得到一个 IConnectionPointContainer:
_cpc = (IConnectionPointContainer)_myObject;
并从中获取我的 IConnectionPoint:
IConnectionPoint _cp;
_cpc.FindConnectionPoint(typeof(IMyCPInterface).GUID, out _cp);
_cp.Advise(this, out _cookie);
我现在不确定释放所有资源的正确方法。 如何正确释放所有创建的资源?
目前我按照下面的方式进行操作,但我不确定我是否正确发布了所有内容:
protected virtual void Dispose(bool pDisposing)
{
if(!_isDisposed)
{
if(pDisposing)
{
//dispose managed
}
if(_cookie > 0 && _cp != null)
{
_cp.Unadvise(_cookie);
_cp = null; //<-- ReleaseComObject(_cp); ?
_cookie = 0;
}
//I don't release _cpc, because it is the same object as _myObject?
if(_myObject != null)
{
Marshal.ReleaseComObject(_myObject);
_myObject = null;
}
_isDisposed = true;
}
}
【问题讨论】:
-
一般情况下:释放引用计数增加的次数。即:查询接口时(通过转换为:((IConnectionPointContainer)_myObject),您应该阅读文档以确定引用计数是否增加(通常是)。Marshal.FinalReleaseComObject 可能会有所帮助:msdn.microsoft.com/en-us/library/…跨度>
-
根据:msdn.microsoft.com/en-us/library/windows/desktop/…,必须释放_cp。 _cpc 也必须被释放,当然 _myObject 也必须被释放,由于 IMyInterface 演员,可能会释放两次。
-
您可以随时测试它,当您完成对象时,引用计数必须为0。