我有一個C#控制檯程序。運行時,它會實例化一些Excel對象,如:(openExcelO)。C#通過Excel過程銷燬多個Excel對象的正確方法銷燬
當程序運行完畢,我有一個關閉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的過程?
謝謝!
您應該在關閉它之後立即嘗試釋放工作簿,然後_then_ close excel,_then_釋放應用程序。 'Quit'是否有布爾重載允許退出而忽略所有錯誤? Word互操作對象的確如此。 – 2013-03-21 01:15:15
[關閉Excel應用程序的正確方法]的可能的重複(http://stackoverflow.com/questions/9581689/proper-way-of-closing-excel-application) – 2013-03-21 01:18:39
還要注意,除了您應該始終[在調用'GC.Collect'](http://stackoverflow.com/a/118776/622391)之前想想很難,你對'GC.Collect'的調用實際上不會幫助你的對象被收集,因爲你的主類仍然擁有對每個COM對象的引用。要使'releaseObject'也清除主引用,請將其更改爲'releaseObject(ref object obj)',因爲在調用obj = null時,該字段本身將設置爲null。 – 2013-03-21 03:03:47