0

可能重复:
终止互操作应用程序进程

我正在使用 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();

        }

请告诉我哪里出错了。

4

1 回答 1

1

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

   sheets = excelWorkBook.Worksheets;

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

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

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

   Marshal.FinalReleaseComObject(sheets);
于 2012-06-22T08:12:57.040 回答