C# Proper Way to Close Multiple Excel Objects With Excel Process Destroyed

与世无争的帅哥 提交于 2019-12-05 21:13:15
Simon MᶜKenzie

It looks like you're not releasing your objects in the correct order - xlApp.Quit probably can't exit cleanly because you still hold a reference to the workbook. You need to release the workbook before you invoke Quit:

xlWorkBook.Close(false, misValue, misValue);
releaseObject(xlWorkBook);

xlApp.Quit();
releaseObject(xlApp);

Credit must go to this StackOverflow answer: there are a couple of other implicit references that you're not closing, i.e., in the following lines:

xlWorkBook = xlApp.Workbooks.Open(...)
xlWorkBook.Sheets["Markowitz"];

The "Workbooks" object isn't being released, and neither is the "Sheets" object. You need to release these references too, i.e.:

var books = xlApp.Workbooks;
books.Open(...);
releaseObject(books);

var sheets = xlWorkBook.Sheets;
xlMarkowitz = (Excel.Worksheet)sheets["Markowitz"];
xlWeights = (Excel.Worksheet)sheets["Weights"];
releaseObject(sheets);

Great advice from Bruce Barker: "Never use two dots with COM objects"!

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