我在C#(ApplicationClass)中使用Excel互操作,并在我的finally子句中放置了以下代码:
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(excelSheet) != 0) { }
excelSheet = null;
GC.Collect();
GC.WaitForPendingFinalizers();
Run Code Online (Sandbox Code Playgroud)
虽然这种工作,Excel.exe即使我关闭Excel后,该过程仍然在后台.只有在我的应用程序手动关闭后才会发布.
我做错了什么,或者是否有其他方法可以确保互操作对象得到妥善处理?
可能重复:
如何在C#中正确清理Excel互操作对象
我用这个函数计算一些数据的线性趋势:
private string Trend(object conocido_y, object conocido_x, object nueva_matriz_x)
{
string result = String.Empty;
try {
Microsoft.Office.Interop.Excel.Application xlApp = new Microsoft.Office.Interop.Excel.Application();
result = ((Array)xlApp.WorksheetFunction.Trend(conocido_y, conocido_x, nueva_matriz_x, true)).GetValue(1).ToString();
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlApp = null;
}
catch (System.Runtime.InteropServices.COMException ex) {
DError.ReportarError(ex, false);
}
catch (Exception ex) {
DError.ReportarError(ex);
}
return result;
}
Run Code Online (Sandbox Code Playgroud)
结果很好,但excel应用程序没有关闭,如果我打开任务管理器进程仍在运行,为什么?