我有一个 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 进程?
谢谢!