微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 动态COM对象是否被视为托管资源?

我有一个动态COM对象作为我班级中的私有字段.我不确定它是否被视为托管资源(GC清理它).
private dynamic _comConnector = null;

_comConnector = Activator.CreateInstance(Type.GetTypeFromProgID("SomeProgId"));

在实现Idispose时,我应该将其清理为托管资源(仅在显式调用dispose()时),还是作为本机资源(从终结器调用dispose(false)时)?

private void dispose(bool disposing)
{
    if (disposing)
    {
        // Free managed resources //

        // --> Should I call Marshal.FinalReleaseComObject(_comConnector) here?
    }

    // Free unmanaged resources //

    // --> Or maybe here?
}

解决方法

它是一个托管资源(基本上是一个Runtime Callable Wrapper),你应该这样清理它. MSDN states that

Each RCW maintains a cache of interface pointers on the COM object it wraps and releases its reference on the COM object when the RCW is no longer needed. The runtime performs garbage collection on the RCW.

即RCW是一个托管非托管COM引用的托管资源.

另外,如果您在应用程序的多个位置使用多个线程,则释放COM对象可能会很危险,如this blog post from Chris Brumme中所述.

如果您以作用域,单线程方式使用COM对象,则可以在完成后对该对象安全地调用ReleaseComObject:希望这是您的情况.

原文地址:https://www.jb51.cc/csharp/100441.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐