gpt4 book ai didi

c# - 无法使用与其底层 RCW 分离的 COM 对象

转载 作者:IT王子 更新时间:2023-10-29 03:54:05 28 4
gpt4 key购买 nike

我有一些从某些 c# dll 调用的 COM 组件。

我还有一个使用该 .dll 的 winforms 应用程序。

当我关闭应用程序时出现此异常:

COM object that has been separated from its underlying RCW cannot be used.

堆栈跟踪显示此异常来自 .dll 中的析构函数。我实现了这个析构函数来调用 COM 中的一些清理方法。

为什么会这样?怎么解决最好?

最佳答案

问题描述如下:

Is it safe to call an RCW from a finalizer?

这里:

Release Excel Object In My Destructor

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.

关于c# - 无法使用与其底层 RCW 分离的 COM 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2260990/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com