Excel后台进程不closures

每次打开并用Iterop读取文件后,Excel后台进程都将保持打开状态。 几次运行下面的方法后,我结束了很多的Excel后台进程。 我意识到这已经在不同的时间问过,但我已经尝试了所有的build议(并在下面的代码中实现它们),没有任何工作。 有人可以帮忙。

public List<double> ReadExcelFile() { Application excelApp = null; Workbooks workbooks = null; Workbook workBook = null; Worksheet worksheet = null; Range excelRange = null; List<double> sheetValues = new List<double>(); try { excelApp = new Application(); workbooks = excelApp.Workbooks; workBook = workbooks.Open(f_inputFilePath, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing); worksheet = workBook.Sheets["Sheet1"]; excelRange = worksheet.UsedRange; object[,] sheetValuesRaw = (object[,])excelRange.get_Value(XlRangeValueDataType.xlRangeValueDefault); for (int i = f_firstNumericValueIndex; i <= sheetValuesRaw.GetLength(0); i++) sheetValues.Add((double)sheetValuesRaw[i, 1]); } finally { workBook.Close(false, Type.Missing, Type.Missing); workbooks.Close(); releaseObject(excelRange); releaseObject(worksheet); releaseObject(workbooks); releaseObject(workBook); excelApp.Quit(); releaseObject(excelApp); } return sheetValues; } private void releaseObject(object obj) { try { Marshal.ReleaseComObject(obj); obj = null; } catch (Exception ex) { obj = null; } finally { GC.Collect(); GC.WaitForPendingFinalizers(); } } 

几个星期前,我在Excel中遇到了一些问题。 我试图通过在try-catch-finally语句中使用Excelfunction的方法来解决这个过程。

所以它看起来像这样:

 public List<double> MyResults() { try { return ReadExcelFile(); } finally { GC.Collect(); GC.WaitForPendingFinalizers(); } } 

你可以调用“MyResults”方法来代替当前有“ReadExcelFile”被调用的地方。

我发现通过使用Interop服务在方法之外的另一个try-catch-finally循环内包装Excel函数,它允许Excel位超出范围,并允许GC收集它们。