C#Excel Interop:在父窗体关闭之前,Excel进程仍保留在内存中

在我的形式中,我正在做一些简单的事情

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

我遵循了“为excel互操作而设计的2点规则”。

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

处置方法执行以下操作。

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

在我的测试中,一旦Excel电子表格打印完成,EXCEL.exe进程不会始终从任务栏中的当前进程中删除。

我究竟做错了什么?


你有没有尝试过调用GC.Collect()?

或者,如果您不想强制所有代的即时垃圾收集,则可以使用using{}

链接地址: http://www.djcxy.com/p/911.html

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

下一篇: Doxygen equivalent for Mathematica?