如何正确清理Excel的互操作的对象? [英] How to properly clean up Excel interop objects?

查看:297
本文介绍了如何正确清理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.

我发现<一个解决我的问题href=\"http://www.velocityreviews.com/forums/showpost.php?s=f87f0674feda4442dcbd40019cbca65b&p=528575&postcount=2\">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);

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

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