C#正确方法closures多个Excel对象与Excel进程销毁

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

当程序运行完毕,我有一个方法closuresExcel(closeExcel),并且应该正确清理Excel进程。 在任务pipe理器中,我可以看到剩下的Excel剩余部分。 closures例程是从互联网的例子拼凑在一起:

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(); } } 

如何更改关机例程以正确closures和清理Excel对象,以便在任务pipe理器中没有延续的Excel进程?

谢谢!

它看起来像你没有按正确的顺序释放你的对象 – xlApp.Quit可能不能干净地退出,因为你仍然持有对工作簿的引用。 您需要调用Quit 之前释放工作簿:

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

信用必须去这个StackOverflow的答案 :有几个其他的隐式引用,你不closures,即在以下几行:

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

“工作簿”对象不被释放,也不是“表格”对象。 你也需要释放这些引用,即:

 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的伟大build议:“不要在COM对象上使用两个点”!