C# Excel automation causes Excel memory leak

前端 未结 1 1509
萌比男神i
萌比男神i 2020-12-10 04:31

I\'m trying to use C# with the COM Interop library to open a set of very heavy excel workbooks. I have to use C#, because I also need to start macros, move some cells aroun

1条回答
  •  自闭症患者
    2020-12-10 05:06

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

    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");
    

    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);
    

    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.

    0 讨论(0)
提交回复
热议问题