我一直在使用一些DirectShow接口来使用C#和数字电视播放数字电视(DVB-T) DirectShow.Net。我最近遇到了运行时错误 COM object that has been separated from its underlying RCW cannot be used.
此错误发生在以下行:
_guideData = _transportInformationFilter as IGuideData;
_transportInformationFilter
是IBaseFilter类型,以前通过DirectShow.Net实用程序函数分配的COM对象。
我认为错误是由于 _transportInformationFilter
以某种方式提前释放,我跟踪它到以下方法(删除错误处理):
private void AttachGuideDataEvent()
{
IConnectionPoint connPoint = null;
IConnectionPointContainer connPointContainer = null;
try
{
connPointContainer = _transportInformationFilter as IConnectionPointContainer;
if (connPointContainer == null) /* error */
var guideDataEventGuid = typeof (IGuideDataEvent).GUID;
connPointContainer.FindConnectionPoint(ref guideDataEventGuid, out connPoint);
if (connPoint == null) /* error */
int cookie;
connPoint.Advise(this, out cookie);
if (cookie == 0) /* error */
_persistIGuideDataEventCookie = cookie;
}
finally
{
if (connPointContainer != null)
Marshal.ReleaseComObject(connPointContainer);
if (connPoint != null)
Marshal.ReleaseComObject(connPoint);
}
}
据我所知, connPointContainer = _transportInformationFilter as IConnectionPointContainer
本来应该打电话给 QueryInterface
在...上 _transportInformationFilter
COM对象,因此需要单独发布。但是,打电话给 Marshal.ReleaseComObject(connPointContainer)
是造成罪魁祸首的原因 _transportInformationFilter
与RCW分开;删除此调用修复了该问题。
鉴于这种, 在什么情况下我需要显式释放COM对象(使用 Marshal.ReleaseComObject
)在C#中避免资源泄漏?