Excel 2010 COM Object Links Not Released

The following code sample worked fine in Excel 2007, but when I installed Excel 2010 (32 bit), it would leave the excel.exe process open if I did not add GC.Collect (). My simple question is: am I doing something wrong? It seems to me that I release everything that I use.

    public override void Update()
    {

        StatusBox.AddStatus("Opening File " + ImportPath);

        Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel.Workbook wb = app.Workbooks.Open(ImportPath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        Microsoft.Office.Interop.Excel.Worksheet ws = (Microsoft.Office.Interop.Excel.Worksheet)wb.Sheets[1];

        Range rng = ws.Cells.SpecialCells(XlCellType.xlCellTypeLastCell, Type.Missing);

        int LastRow = rng.Row;

        StatusBox.AddStatus(LastRow.ToString() + " Rows Found in File");


        StatusBox.AddStatus("Closing File " + ImportPath);

        System.Runtime.InteropServices.Marshal.ReleaseComObject(rng);
        rng = null;

        System.Runtime.InteropServices.Marshal.ReleaseComObject(ws);
        ws = null;

        wb.Close(true, ImportPath, null);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(wb);
        wb = null;

        GC.Collect();

        app.Quit();
        System.Runtime.InteropServices.Marshal.ReleaseComObject(app);
        app = null;
    }
+3
source share
1 answer

You need to call GC.Collect / GC.WaitForPendingFinalizers and Marshall.FinalReleaseComObject.

See my answer for more details:

How to clean Excel interaction objects correctly?

, (, -, ) " " , . - , Excel , , - . .

GC.WaitForPendingFinalizers GC.Collect. , . (GC.Collect , , , COM-, , COM-, " " ). GC.Collect GC.WaitForPendingFinalizers Marshall.FinalReleaseComObject .

, , GC.Collect GC.WaitForPendingFinalizers COM-, , Marshall.FinalReleaseComObject COM-, .

-

+1

Source: https://habr.com/ru/post/1771757/


All Articles