我正在使用下面的方法。执行此代码块后,我发现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)。 –