开发者

Why does excel remain open? [duplicate]

开发者 https://www.devze.com 2022-12-13 15:15 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: How to properly clean up Excel interop 开发者_运维知识库objects in C#
This question already has answers here: Closed 10 years ago.

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?


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();


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.


Try using

xlApp.Application.Quit();

instead of

xlApp.Quit();

I ran into exactly the same issue recently :)


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

0

精彩评论

暂无评论...
验证码 换一张
取 消