4

我有一个 C# 控制台程序。当它运行时,它会实例化一些 Excel 对象,例如:(openExcelO)。

程序运行完毕后,我有一个关闭 Excel 的方法(closeExcel),它应该可以正确清理 Excel 进程。在任务管理器中,我可以看到剩余的 Excel 残余。关闭程序是从互联网示例中拼凑而成的:

    private void openExcelO (string dir) {

        try {
            xlApp = new Excel.Application();
            xlWorkBook = xlApp.Workbooks.Open(dir + "PortfolioOptimization5.xlsm",
                0, false, 5, "", "", true, 
                Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, 
                "\t", false, false, 0, true, 1, 0);
            xlMarkowitz = (Excel.Worksheet)xlWorkBook.Sheets["Markowitz"];
            xlWeights = (Excel.Worksheet)xlWorkBook.Sheets["Weights"];

        } catch (Exception ex) {
            ReportError("PortfolioOptimization", "openExcel", ex.ToString());
        }

    }


    private void closeExcel () {
        object misValue = System.Reflection.Missing.Value;
        try {

            if (xlWeights != null) releaseObject(xlWeights);
            if (xlMarkowitz != null) releaseObject(xlMarkowitz);

            xlWorkBook.Close(false, misValue, misValue);
            if (xlApp != null) xlApp.Quit();

            if (xlWorkBook != null) releaseObject(xlWorkBook);
            if (xlApp != null) releaseObject(xlApp);

        } catch (Exception ex) {
            ReportError("PortfolioOptimization", "closeExcel", ex.ToString());
        }
    }


    private void releaseObject (object obj) {
        try {
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj);
            obj = null;
        } catch (Exception ex) {
            obj = null;
            ReportError("PortfolioOptimization", "releaseObject", "Unable to release object " + ex.ToString());
        } finally {
            GC.Collect();
        }
    }

如何更改关闭例程以正确关闭和清理 Excel 对象,以便任务管理器中没有延迟的 Excel 进程?

谢谢!

4

1 回答 1

9

看起来您没有以正确的顺序释放对象 -xlApp.Quit可能无法干净地退出,因为您仍然持有对工作簿的引用。您需要在调用之前Quit释放工作簿:

xlWorkBook.Close(false, misValue, misValue);
releaseObject(xlWorkBook);

xlApp.Quit();
releaseObject(xlApp);

信用必须归功于这个 StackOverflow 答案:还有一些其他的隐式引用你没有关闭,即在以下几行中:

xlWorkBook = xlApp.Workbooks.Open(...)
xlWorkBook.Sheets["Markowitz"];

“Workbooks”对象没有被释放,“Sheets”对象也没有被释放。您还需要发布这些引用,即:

var books = xlApp.Workbooks;
books.Open(...);
releaseObject(books);

var sheets = xlWorkBook.Sheets;
xlMarkowitz = (Excel.Worksheet)sheets["Markowitz"];
xlWeights = (Excel.Worksheet)sheets["Weights"];
releaseObject(sheets);

Bruce Barker的好建议:“永远不要在 COM 对象中使用两个点”!

于 2013-03-21T01:26:20.257 回答