C# Excel Interop : Excel process remains in memory until parent form closed
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?
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
上一篇: 税收查询(每个邮编等)?