Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Excel Interop : Excel process remains in memory until parent form closed

Tags:

c#

excel

interop

In my form I am doing something as simple as

private void btnPrintPickList_Click(object sender, EventArgs e)
{
    using (var salesRpt = new SalesOrder(CurrentItem()))
    {
        salesRpt.CreateSpreadSheet();
        salesRpt.Dispose();
    }
}

I have followed the "no 2 dots rule for excel interop".

protected ExcelSheet(bool documentVisible, XlPageOrientation orientation)
{
    ExcelApplication = new Application {Visible = documentVisible};
    WorkBooks = ExcelApplication.Workbooks;
    WorkBook = WorkBooks.Add(XlSheetType.xlWorksheet);
    SheetList = WorkBook.Worksheets;
    Orientation = orientation;
    WorkSheet = (Worksheet) ExcelApplication.ActiveSheet;
}

public Application ExcelApplication { get; private set; }
public Workbook WorkBook { get; private set; }
public Workbooks WorkBooks { get; private set; }
public Worksheet WorkSheet { get; private set; }
public Sheets SheetList { get; private set; }
public XlPageOrientation Orientation { get; private set; }

the dispose method does the following.

    public void Dispose()
    {
        for (int i = 1; i <= SheetList.Count; i++)
        {
            Marshal.FinalReleaseComObject(SheetList[i]);
        }
        //Marshal.FinalReleaseComObject(WorkSheet);
        Marshal.FinalReleaseComObject(SheetList);
        Marshal.FinalReleaseComObject(WorkBook);
        WorkBooks.Close();
        Marshal.FinalReleaseComObject(WorkBooks);
        ExcelApplication.Quit();
        Marshal.FinalReleaseComObject(ExcelApplication);
        WorkSheet = null;
        SheetList = null;
        WorkBook = null;
        WorkBooks = null;
        ExcelApplication = null; 
    }

In my testing, the EXCEL.exe process does not consistently get removed from the current processes in the taskbar once the Excel spreadsheet is printed.

What am I doing wrong?

like image 851
CF_Maintainer Avatar asked May 06 '10 15:05

CF_Maintainer


1 Answers

Have you tried calling GC.Collect()?

Alternatively, you could use using{} if you don't want to force an immediate garbage collection of all generations

like image 57
Robben_Ford_Fan_boy Avatar answered Sep 26 '22 08:09

Robben_Ford_Fan_boy