问题描述
我有一些从 c# dll 调用的 COM 组件.
I have some COM component which I call from some c# dll.
我还有一个使用该 .dll 的 winforms 应用程序.
I also have a winforms app that uses that .dll.
当我关闭应用程序时,我得到了这个异常:
When I close the app I get this exception:
已分离的 COM 对象从其基础 RCW 不能用过.
COM object that has been separated from its underlying RCW cannot be used.
堆栈跟踪显示此异常来自 .dll 中的析构函数.我实现了这个析构函数来调用 COM 中的一些清理方法.
The stack trace shows this exception comes from a destructor in the .dll. I implemented this destructor to call some cleanup method in the COM.
为什么会这样?怎么解决最好?
Why does this happen? How is it best to solve it?
推荐答案
问题描述如下:
从终结者?
这里:
在我的析构函数中释放 Excel 对象
问题在于,不仅是这些对象的时间是否要被垃圾收集不确定,但是垃圾收集的顺序终结器被称为也是不确定的.在这种情况下,一个Runtime Callable Wrapper 还有一个终结器,它调用Marshal.FinalReleaseComObject 本身,其结果为减少栅栏 COM 端的引用计数,以便这个 COM 对象可以被释放.但由于在其中的顺序finalizers 被调用是不确定的,很有可能是对象引用将触发的 COM 对象的终结器在对象的终结器之前.所以你的代码终结器有时可以工作,但大多数时候,一个或多个您的对象引用将具有的运行时可调用包装器已经调用了它们的终结器,并且底层的 COM 对象将在你的终结器开始执行它的代码之前就已经发布了.
The trouble is that not only is the timing as to when these objects are to be garbage collected uncertain, but the order in which the finalizers are called is also nondeterministic. In this case, a Runtime Callable Wrapper also has a finalizer, which calls Marshal.FinalReleaseComObject on itself, which has the result of decrementing the reference count on the COM side of the fence so that this COM object can be released. But since the order in which the finalizers are called is uncertain, it is very possible that the finalizers for the COM objects that your object references will fire before the finalizer for your object. So the code within your finalizer could work sometimes, but, most of the time, one or more of the Runtime Callable Wrappers that your object references will have already had their finalizers called and the underlying COM object will have been released before your finalizer gets to execute its code.
这篇关于无法使用已与其底层 RCW 分离的 COM 对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!