C#Excel Interop:Excel进程保留在内存中,直到父表单关闭

时间:2010-05-06 15:29:49

标签: c# excel interop

在我的表格中,我正在做一些简单的事情

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

我遵循了“excel interop的无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; }

dispose方法执行以下操作。

    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进程不会始终从任务栏中的当前进程中删除。

我做错了什么?

1 个答案:

答案 0 :(得分:3)

您是否尝试过调用GC.Collect()?

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