发布COM对象的正确方法? [英] Proper way of releasing COM objects?

查看:147
本文介绍了发布COM对象的正确方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时当我结束应用程序并尝试释放一些COM对象时,我会在调试器中收到一个警告:

Sometimes when I end the application and it tries to release some COM objects, I receive a warning in the debugger:


检测到RaceOnRCWCleanUp

如果我编写一个使用COM对象的类,在 IDisposable.Dispose 中实现 IDisposable 并调用 Marshal.FinalReleaseComObject $ c>以正确地释放它们?

If I write a class which uses COM objects, do I need to implement IDisposable and call Marshal.FinalReleaseComObject on them in IDisposable.Dispose to properly release them?

如果 Dispose 他们在终结器或者GC会自动释放它们吗?现在我在终结器中调用 Dispose(false),但我不知道如果这是正确的。

If Dispose is not called manually then, do I still need to release them in the finalizer or will the GC release them automatically? Now I call Dispose(false) in the finalizer but I wonder if this is correct.

我使用的COM对象也有一个类侦听的事件处理程序。显然,事件是在另一个线程上产生的,那么如果在处理类时触发该事件,我该如何正确处理呢?

The COM object I use also have an event handler which the class listens to. Apparently the event is raised on another thread, so how do I correctly handle it if it is fired when disposing the class?

推荐答案

基于我使用不同的COM对象(进程中或进程外)的经验,我建议每个COM / .NET边界交叉一个Marshal.ReleaseComObject(如果一个实例引用COM对象,以检索另一个COM引用)。

Based on my experience using different COM objects (in-process or out-of-process) I would suggest one Marshal.ReleaseComObject per one COM/ .NET boundary crossing (if for an instance you reference COM object in order to retrieve another COM reference).

我遇到很多问题,只是因为我决定推迟COM interop清理到GC。
另请注意,我从不使用Marshal.FinalReleaseComObject - 一些COM对象是单例,并且不能很好地与这样的对象。

I have run into many issues just because I decided to postpone COM interop cleanup to GC. Also please notice, I never use Marshal.FinalReleaseComObject - some COM objects are singletons and it doesn't work well with such objects.

在托管在finalizer中的对象(或者从众所周知的IDisposable实现中的Dispose(false))被禁止。在终结器中不能依赖任何.NET对象引用。您可以发布 IntPtr ,但不能释放COM对象,因为它已经可以清除了。

Doing anything in managed objects inside finalizer (or Dispose(false) from the well-known IDisposable implementation) is forbidden. You must not rely on any .NET object reference in the finalizer. You can release IntPtr, but not COM object as it could already be clean up.

这篇关于发布COM对象的正确方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆