我正在使用下面的方法。執行此代碼塊後,我發現Microsoft Excel仍然通過檢查任務管理器在後臺運行。Excel互操作對象不被釋放
編輯:正好一個 Microsoft Excel後臺進程仍然存在。我剛剛添加了這個功能,因爲當我第一次開始使用Excel和Interop COM對象時,有時許多進程將在函數完成執行後繼續運行。
如何確保在我的當前函數執行後Excel不會在後臺運行?
,因爲一些功能最終需要他們,我聲明這些變量具有全局範圍:
private Excel.Application xls = null;
private Excel.Workbooks workBooks = null;
private Excel.Workbook workBook = null;
private Excel.Sheets sheets = null;
private Excel.Worksheet workSheet = null;
此方法可用於檢查是否在給定的工作簿是否存在片:
private bool sheetExists(string searchString)
{
xls = new Excel.Application();
workBooks = xls.Workbooks;
workBook = workBooks.Open(workbookPath); // <- Where the workbook is saved
sheets = workBook.Sheets;
bool isFound = false;
foreach (Excel.Worksheet sheet in sheets)
{
// Check the name of the current sheet
if (sheet.Name == searchString)
{
Marshal.ReleaseComObject(sheet);
isFound = true;
break;
}
Marshal.ReleaseComObject(sheet);
}
cleanUp(true, xls, workBooks, workBook, sheets);
return isFound;
}
此功能用於釋放COM對象:
private void cleanUp(bool saveTrueFalse, params object[] comObjects)
{
workBook.Close(saveTrueFalse);
xls.Application.Quit();
xls.Quit();
foreach (object o in comObjects)
{
Marshal.ReleaseComObject(o);
}
workSheet = null;
sheets = null;
workBook = null;
workBooks = null;
xls = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.WaitForPendingFinalizers();
}
又一個不瞭解垃圾收集器如何工作的例子。這裏已經覆蓋了很多次,[喜歡這裏](http://stackoverflow.com/questions/25134024/clean-up-excel-interop-objects-with-idisposable/25135685#25135685)。 –