如何正确清理Excel的互操作的对象?

问题描述:

我使用C#( ApplicationClass )对Excel互操作,并已放在下面的code在我的最后条款:

I'm using the Excel interop in C# (ApplicationClass) and have placed the following code in my finally clause:

while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet) != 0) { }
excelSheet = null;
GC.Collect();
GC.WaitForPendingFinalizers();

虽然,这类作品的 EXCEL.EXE 过程仍在即使我关闭Excel的背景。一旦我的申请被手动关闭它仅释放。

Although, this kind of works the Excel.exe process is still in the background even after I close Excel. It is only released once my application is manually closed.

任何人都知道我在做什么错了,还是有一个替代,以确保互操作对象妥善处理。

Anyone realize what I am doing wrong, or has an alternative to ensure interop objects are properly disposed of.

Excel不退出,因为你的应用程序中仍保持引用COM对象。

Excel does not quit because your app is still holding references to COM objects.

我猜你调用COM对象的至少一个成员,而不将其分配给一个变​​量。

对于我来说,是的 excelApp.Worksheets 的我直接使用,无需将其分配给一个变​​量对象:

For me it was the excelApp.Worksheets object which I directly used without assigning it to a variable:

Worksheet sheet = excelApp.Worksheets.Open(...);
...
Marshal.ReleaseComObject(sheet);

我不知道的是,国内C#创建了一个包装在工作表这并没有得到我的code释放(因为我没有意识到这一点)COM对象并且是Excel的为什么不卸载的原因。

What I didn't know was that internally C# created a wrapper for the Worksheets COM object which didn't get released by my code (because I wasn't aware of it) and was the cause why Excel was not unloaded.

我发现this页面,其中也有对COM对象在C#中使用一个很好的规则:

I found the solution to my problem on this page, which also has a nice rule for the usage of COM objects in C#:

切勿使用2点与COM对象。

Never use 2 dots with com objects.

所以这方面的知识上面做的正确的方法是:


So with this knowledge the right way of doing the above is:

Worksheets sheets = excelApp.Worksheets; // <-- the important part
Worksheet sheet = sheets.Open(...);
...
Marshal.ReleaseComObject(sheets);
Marshal.ReleaseComObject(sheet);