Why does excel remain open? [duplicate]

2020-03-30 02:52发布

Possible Duplicate:
How to properly clean up Excel interop objects in C#

I've this function that I use to calculate the linear trend of some data:

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;
}

the results are fine but the excel app doesn't close, if I open the task manager the process is still running, why?

4条回答
聊天终结者
2楼-- · 2020-03-30 02:59

Is your function creating an error? If so the Quit() is never reached. You may want to put the Quit and ReleaseComObject in a finally block.

查看更多
家丑人穷心不美
3楼-- · 2020-03-30 03:09

Excel is a COM Automation Server.

Even though you call Application.Quit() and you Release the Reference to the COM object, the exe itself will not end. You will still be able to see it in task manager. Making further calls to Excel will use the running instance.

The Excel instance will exit after your application (thread, session, etc..) closes.

Ever get "RPC server not found/running" type COM errors? Now you know why.

See also (this has been asked many times on SO):

c# and excel automation - ending the running instance

查看更多
smile是对你的礼貌
4楼-- · 2020-03-30 03:16

I remember having seen that, after ReleaseComObject(), a forced GC pass is due for the object to be released and excel to finally die.

Also, I don't see it in that snippet, but you have to ReleaseComObject() in any sheet or other Excel object you might have gotten a handle on (is result such a thing?).

ReleaseComObject(result);
app.Aplication.Quit();
ReleaseComObject(app);
GC.Collect();
查看更多
来,给爷笑一个
5楼-- · 2020-03-30 03:22

Try using

xlApp.Application.Quit();

instead of

xlApp.Quit();

I ran into exactly the same issue recently :)

查看更多
登录 后发表回答