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

匿名 (未验证) 提交于 2019-12-03 03:06:01

问题:

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?

回答1:

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!