如何正确清理C#中的互操作对象 [英] How to properly clean up interop objects in C#

查看:108
本文介绍了如何正确清理C#中的互操作对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个关于
的问题的答案如何正确地清理c#中的excel互操作对象。

This is a follow on question to How to properly clean up excel interop objects in c#.

gyst是在Excel命名空间中使用链接调用(例如ExcelObject.Foo.Bar())可以防止COM对象的垃圾回收。相反,应该显式地创建对所使用的每个COM对象的引用,并使用Marhsal.ReleaseComObject()明确地释放它们。

The gyst is that using a chaining calls together (eg. ExcelObject.Foo.Bar() ) within the Excel namespace prevents garbage collection for COM objects. Instead, one should explicitly create a reference to each COM object used, and explicitly release them using Marhsal.ReleaseComObject().

是否仅在特定于Excel COM对象的链接调用之后不释放COM对象的行为?每当一个COM对象被使用时,应用这种模式是否过度?

Is the behaviour of not releasing COM objects after a chained call specific to Excel COM objects only? Is it overkill to apply this kind of pattern whenever a COM object is in use?

推荐答案

出于两个原因,在处理Office应用程序时与其他许多COM库进行处理时一样更为重要。 p>

It's definitely more important to handle releases properly when dealing with Office applications than many other COM libraries, for two reasons.


  1. Office应用程序作为进程服务器运行,而不是in-proc库。如果您无法正确清理,则会导致进程正在运行。

  2. 即使您调用Application.Quit,Office应用程序(尤其是Excel IIRC)也不能正常终止,如果有未完成的参考对于COM对象,

对于常规的in-proc COM库,未能正确清理的后果并不那么戏剧化。当您的进程退出时,所有in-proc库都将随之消失。如果您不再需要对象上的某个对象调用ReleaseComObject,那么在对象被最终确定后,它仍然会被保留。

For regular, in-proc COM libraries, the consequences of failing to clean up properly are not so dramatic. When your process exits, all in-proc libraries goes away with it. And if you forget to call ReleaseComObject on an object when you no longer need it, it will still be taken care of eventually when the object gets finalized.

不可以写乱码。

这篇关于如何正确清理C#中的互操作对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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