Problem with hanging interop COM objects

二次信任 提交于 2019-12-05 05:43:03

Excel cannot terminate until all its out-of-process objects are released. So it just hides its user interface and keeps running. Until either your program quits or you null all your Excel object references and the finalizer thread runs. Quitting your program would be an obvious solution. Or you can force the finalizer thread to run with:

GC.Collect();
GC.WaitForPendingFinalizers();

ReleaseComObject() rarely works because it is so easy to forget an intermediary COM object reference. Like WorkBooks[index], that's an enumerator you don't see. Letting the GC make that decision for itself would be the wiser choice, if you keep running and doing work then that will happen.

Possibly Excel.exe is still open because the user opened another document in the same instance of the Excell application. In that case, you should probably not kill the Excel.exe process.

If you ensure that you close all the documents you opened, and release all the objects that you created, then why is it important to you to ensure that Excel.exe terminates? Maybe the process is serving another application, or the user?

There could be many reasons (including Ran's), but one I see a lot with MapPoint (another Microsoft app with a COM interface) is that you must ensure that ALL object references are cleared so that the garbage collector can clean them up. One lowly object hanging around is enough to stop the application from closing down and exiting the process list.

Gary

If I open the Excel application and workbook with:

Excel.Application app = new Excel.Application();
Excel.Workbook wb = app.Workbooks.Open(...);

Then I use the wb.Close(), app.Quit() methods in a finally statement (or other appropriate closing event). This cleans up the Exel.exe process. No need to call the Marshall.ReleaseComObject or GC methods.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!