C#4做COM的时候需要调用Marshal.ReleaseComObject吗?
我有 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
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
清理内存有两种方法。
COM 组件使用引用计数算法来回收内存。每当您不需要 com 组件的引用时,您都可以调用它。但通常我的方法是创建一个虚拟堆栈并删除引用,如下面的 C# 源代码。只要 RCW 处于活动状态,.NET 就保证 COM 组件处于活动状态。当 RCW 被垃圾收集时,释放方法被调用。没有必要在代码中调用release。但它不影响GC周期。
There are two types of approaches in terms of cleaning memory.
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.