我有一个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进程?
谢谢!
答案 0 :(得分:7)
看起来你没有以正确的顺序发布你的对象 - xlApp.Quit
可能无法完全退出,因为你仍然持有对工作簿的引用。您需要在调用Quit
之前发布工作簿:
xlWorkBook.Close(false, misValue, misValue);
releaseObject(xlWorkBook);
xlApp.Quit();
releaseObject(xlApp);
信用必须转到this StackOverflow answer:还有一些其他隐含的引用,你没有关闭,即,在以下几行:
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对象中使用两个点”!