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

前端之家收集整理的这篇文章主要介绍了C#Excel Interop:Excel进程保留在内存中,直到父表单关闭前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在我的形式中,我正在做一些简单的事情
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进程不会始终从任务栏中的当前进程中删除.

我究竟做错了什么?

解决方法

你试过调用GC.Collect()吗?

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

猜你在找的C#相关文章