【发布时间】:2020-01-14 04:42:45
【问题描述】:
目前我有幸编写 C# 代码从 Excel 文件中读取内容。我正在使用 Nuget Excel 互操作来完成此操作。
我尝试遵循这篇很棒的博文中给出的建议:https://www.add-in-express.com/creating-addins-blog/2013/11/05/release-excel-com-objects/
但即使将所有内容放入最后释放的变量中,当我开始访问单元格时(输入 Range),Excel 进程也不会死。
因此我的问题是:当我这样做时:
Application excel = new Application();
_toBeReleased.Add(excel);
DoStuff(excel);
...
void DoStuff(Application excel2)
{
...
excel2也需要释放吗?因为引用被赋予了byval 到方法中?
【问题讨论】:
-
Excel 是一件令人头疼的事情,我不得不做很多感觉非常不必要的工作来清除你所期望的 Excel。包括强制垃圾运行,我没有使用 nuget 包,我使用的是直接的办公室互操作,但我想它并没有什么不同。
-
您只有一个对本机 COM 对象的引用(RCW):docs.microsoft.com/en-us/dotnet/standard/native-interop/…。您是否尝试只调用 excel.Quit() ?
-
"...当我开始访问单元格..." - 顺便说一下,虽然通常情况下每个 COM 对象只有一个 RCW,但该规则
does not apply to items in a COM collection由 RCW 曝光。每当您迭代 RCW“COM 集合”时,RCW representation of the COM collection returns a new RCW each time you fetch an item from the collection irrespective of whether it is the same index 违反了 c++ 开发人员在此过程中习惯的一些 COM 规则。