C#4做COM的时候需要调用Marshal.ReleaseComObject吗?

发布于 2024-11-18 13:52:07 字数 118 浏览 0 评论 0原文

我有 VS2010 并向我的项目添加了对 COM 库的引用,并且 VS 在项目中嵌入了主要互操作。

如果我引用COM库中的对象并且我想快速处理它们而不等待GC,是否需要调用ReleaseComObject?

I have VS2010 and added a reference to a COM library to my project and VS embedded a primary interop inside the project.

If I reference objects from the COM library and I want to dispose of them quickly without waiting for the GC, is it needed to call ReleaseComObject ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怪异←思 2024-11-25 13:52:07

Marshal.ReleaseComObject 提供了一种方法,可以立即从托管代码中使用该 COM 对象的任何位置删除对该 COM 对象的引用(因为它从持有该对象的 RCW 中释放了底层 IUnknown)。

正如 Hans 所指出的,通常正确的做法是简单地将对象置为 null,以允许 CLR 和 GC 在适当的时间销毁 COM 对象。

然而,在需要立即采取行动的情况下(COM 对象持有昂贵/稀缺的资源,或者可能在关闭期间排序非常复杂),调用 ReleaseComObject 可能是正确的做法。

马丁

Marshal.ReleaseComObject provides a way to immediately drop references to this COM object from everywhere it is being consumed within managed code (because it releases the underlying IUnknown from the RCW that is holding it).

As Hans notes, the generally right course is to simply null your object allow the CLR and GC to do the COM object destruction at the appropriate time.

However, in situations where you need immediate action (COM object holds expensive/scarce resources, or perhaps during shutdown where the sequencing is very complex), calling ReleaseComObject can be the right thing to do.

Martyn

赤濁 2024-11-25 13:52:07

清理内存有两种方法。

  • 引用计数算法
  • 垃圾收集

COM 组件使用引用计数算法来回收内存。每当您不需要 com 组件的引用时,您都可以调用它。但通常我的方法是创建一个虚拟堆栈并删除引用,如下面的 C# 源代码。只要 RCW 处于活动状态,.NET 就保证 COM 组件处于活动状态。当 RCW 被垃圾收集时,释放方法被调用。没有必要在代码中调用release。但它不影响GC周期。

void DoSth
{
       {
            代码的 RunTimeCallableWrapper 区域
            释放通讯对象
       }  
 }

There are two types of approaches in terms of cleaning memory.

  • Reference Counting Algorithms
  • Garbage Collection

COM components use reference counting algorithm to reclaim memory. Whenever you do not need a reference of a com component you can call it. But Usually my approach is creating a virtual stack and deleting references like the source code below in C#. .NET guarantees as long as RCW is alive COM components is alive. When RCW is garbage collected release method is invoked. It is not necessary to call release in your code. But it does not effect gc cycles.

void DoSth
{
       {
            RunTimeCallableWrapper area for the code
            ReleaseComObject
       }  
 }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文