在做COM时,是否有必要在C#4中调用Marshal.ReleaseComObject? [英] Is it necessary to call Marshal.ReleaseComObject in C#4 when doing COM?

查看:436
本文介绍了在做COM时,是否有必要在C#4中调用Marshal.ReleaseComObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有VS2010并添加了一个COM库的引用到我的项目和VS嵌入项目内的主互操作。

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

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

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 ?

推荐答案

Marshal.ReleaseComObject一种方法来立即从引用到该COM对象的任何地方,在托管代码中被消耗(因为它从持有它的RCW释放底层IUnknown)。

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).

正如Hans所说,一般来说,正确的做法是简单地清空对象,允许CLR和GC在适当的时候执行COM对象销毁。

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.

但是,在需要立即执行操作的情况下(COM对象持有昂贵/稀缺的资源,或者可能在关机时序列非常复杂),调用ReleaseComObject可以是正确的事情。

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时,是否有必要在C#4中调用Marshal.ReleaseComObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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