且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

C# Excel 自动化导致 Excel 内存泄漏

更新时间:2023-02-08 20:54:57

在使用 MS Office COM Interop 库时,我遇到了一些避免内存泄漏的方法:

When using the MS Office COM Interop libraries, there are a couple of things I've come across to avoid the memory leaks:

首先,不要使用两个点"是记住它的***方式,但基本上,始终将新的 COM 对象引用分配给新变量,不要链调用成员,即使 Intellisense 鼓励这样做.链式调用会在后台执行一些阻止 .NET 框架正确发布的操作.以下是我用于启动 Excel 报告的一些代码:

First, "Don't use two dots" is the best way to remember it, but basically, always assign a new COM object reference to a new variable, do not chain-call members, even if Intellisense encourages it. Chained calling does some stuff in the background that prevents proper release by the .NET framework.. Here is some code I use for starting an Excel report:

//use vars for every COM object so references don't get leftover
//main Excel app
var excelApp = new Application();
var workbooks = excelApp.Workbooks;

//workbook template
var wbReport = workbooks.Add(@"C:MyTemplate.xltx");

//Sheets objects for workbook
var wSheetsReport = wbReport.Sheets;
var wsReport = (Worksheet)wSheetsReport.get_Item("Sheet1");

其次,为每个以创建逆序创建的变量调用Marshal.ReleaseComObject(),并在此之前调用几个垃圾收集方法:

Secondly, Call Marshal.ReleaseComObject() for each variable created in reverse order of creation, and call a couple of garbage collection methods before doing so:

//garbage collector
GC.Collect();
GC.WaitForPendingFinalizers();

//cleanup
Marshal.ReleaseComObject(wsReport);
Marshal.ReleaseComObject(wSheetsReport);
Marshal.ReleaseComObject(wbReport);
Marshal.ReleaseComObject(workbooks);
Marshal.ReleaseComObject(excelApp);

每次使用 Excel 时都使用这个方案解决了我的记忆问题,虽然我们不能像以前那样使用链接成员很乏味和悲伤.

Using this scheme every time I use Excel has solved my memory issues, though it is tedious and sad we can't use the chained members the way we're used to.