什么时候使用ReleaseComObject和FinalReleaseComObject? [英] When to use ReleaseComObject vs FinalReleaseComObject?

查看:1379
本文介绍了什么时候使用ReleaseComObject和FinalReleaseComObject?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我何时应使用 Marshal.FinalReleaseComObject Marshal.ReleaseComObject



使用 Marshal.FinalReleaseComObject 有什么危险吗?

FinalReleaseComObject 中有一些美德,它会更快崩溃你的程序。 已经从其底层RCW分离的COM对象不能使用是CLR告诉你照顾COM引用计数自己,而不是把它留在CLR是一个错误。你的里程可能不同,你不能真正相信它的工作在你的开发机上得到它正确。确保在将代码部署到客户计算机时实施良好的错误报告。



优点是代码中只有一个位置,您错了, FinalReleaseComObject 调用。当你使用 ReleaseComObject 时,它变得很模糊。因为这将不会被检测到一段时间,当CLR调用最终的 IUnknown :: Release()时,破坏您的程序,破坏对象。远离不正确的 ReleaseComObject 调用。但是这是最后的情景,更可能的结果是,呼叫只是没有任何区别,因为你错过了困难的。像 mumble [foo] ,这是一个非常难以看到被使用的索引器参考。



,我的建议是显而易见的:不要这样做。你正在与一个永远不会错误的机器竞争。这只是一个有点慢。一个非常好的现实生活报告是此处。 无声刺客部分是最相关的。



如果绝对必要让COM服务器立即退出,那么让机器来处理所有的引用计数你使用GC.Collect()。但是请记住,你必须正确地发出呼叫,如果你想要在调试时也工作。它不会在使用COM对象的同一方法中工作,在此答案中有解释。将它放在调用方法中。


When should I use Marshal.FinalReleaseComObject vs Marshal.ReleaseComObject?

Is there any danger in using Marshal.FinalReleaseComObject?

解决方案

There's some virtue in FinalReleaseComObject, it will crash your program quicker. "COM object that has been separated from its underlying RCW cannot be used" is the CLR telling you that you taking care of COM reference counts yourself instead of leaving it up the CLR was a mistake. Your mileage may vary, you cannot really trust to get it right when it works on your dev machine. Make sure you implement good error reporting when you deploy the code to your customer's machine.

The virtue is that there's only one place in your code where you got it wrong, the FinalReleaseComObject call. It gets much fuzzier when you use ReleaseComObject. Because that will go undetected for a while, crashing your program when the CLR calls the final IUnknown::Release(), the one that destroys the object. Very far removed from an incorrect ReleaseComObject call. But that's the doomsday scenario, the more likely outcome is that the call just doesn't make any difference because you missed the hard ones. Like mumble["foo"], an indexer reference that is so very hard to see being used.

Well, my advice is obvious: don't do this. You are competing with a machine that never gets it wrong. It is merely a bit slow at doing so. A very good "report from real life" is available here. The "silent assassin" section is most relevant.

If it is absolutely essential to get a COM server to exit instantly then let the machine take care of getting all the reference counts to 0. You do so with GC.Collect(). But do keep in mind that you have to place that call correctly if you want this to also work when you debug. It won't work in the same method that uses the COM objects, explained in this answer. Put it in the calling method instead.

这篇关于什么时候使用ReleaseComObject和FinalReleaseComObject?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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