【问题标题】:Kill EXEL.EXE process while using Microsoft.Office.Interop.Excel [duplicate]使用 Microsoft.Office.Interop.Excel 时终止 EXEL.EXE 进程 [重复]
【发布时间】:2012-11-24 03:51:21
【问题描述】:

可能重复:
Killing an interop Application process

我正在使用 Microsoft.Office.Interop.Excel 从 Excel 中获取数据。即使我清除了 COM 对象,它仍然会在后台留下一些 EXEL.EXE 实例。请检查下面的代码。

finally
        {
            if (cells != null) Marshal.FinalReleaseComObject(cells);
            if (range != null) Marshal.FinalReleaseComObject(range);
            if (sheets != null) Marshal.FinalReleaseComObject(sheets);
            if (workSheet != null) Marshal.FinalReleaseComObject(workSheet);
            if (excelWorkBook != null)
            {
                excelWorkBook.Close(Type.Missing, Type.Missing, Type.Missing);
                Marshal.FinalReleaseComObject(excelWorkBook);
            }
            if (excelWorkbooks != null) Marshal.FinalReleaseComObject(excelWorkbooks);

            if (excel != null)
            {
                excel.Quit();
                Marshal.FinalReleaseComObject(excel);
            }
            cells = null;
            range = null;
            sheets = null;
            workSheet = null;
            excelWorkBook = null;
            excelWorkbooks = null;
            excel = null;

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();

        }

请告诉我哪里出错了。

【问题讨论】:

  • 进行了相当广泛的清理,但是 finalreleasecomobject 列表中缺少“工作表”?
  • 请检查上面编辑的代码。EXEL.EXE仍然在后台。
  • 如果您的帖子中有编辑过的代码,则不会清理其中的“表格”。我也发布了一个答案,因为在其中使用标记更容易;)

标签: kill-process


【解决方案1】:

唯一没有释放的变量是sheets,定义为:

   sheets = excelWorkBook.Worksheets;

再一次,工作表从不使用,因此可以完全省略,因为工作表被分配为:

   workSheet = (Worksheet)excelWorkBook.Worksheets["Sheet1"]; //doesn't use sheets, so sheets can be omitted

或者如果需要工作表,如果它也已发布,我的测试显示 excel 进程关闭(在应用程序结束之前,在应用程序结束后它总是成功关闭)

   Marshal.FinalReleaseComObject(sheets);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-06
    • 2018-07-28
    • 1970-01-01
    • 2011-04-02
    • 2011-09-19
    • 1970-01-01
    相关资源
    最近更新 更多