c# - How do I properly clean up Excel interop objects? -
i'm using excel interop in c# (applicationclass
) , have placed following code in clause:
while (system.runtime.interopservices.marshal.releasecomobject(excelsheet) != 0) { } excelsheet = null; gc.collect(); gc.waitforpendingfinalizers();
although kind of works, excel.exe
process still in background after close excel. released once application manually closed.
what doing wrong, or there alternative ensure interop objects disposed of?
excel not quit because application still holding references com objects.
i guess you're invoking @ least 1 member of com object without assigning variable.
for me excelapp.worksheets object directly used without assigning variable:
worksheet sheet = excelapp.worksheets.open(...); ... marshal.releasecomobject(sheet);
i didn't know internally c# created wrapper worksheets com object didn't released code (because wasn't aware of it) , cause why excel not unloaded.
i found solution problem on this page, has nice rule usage of com objects in c#:
never use 2 dots com objects.
so knowledge right way of doing above is:
worksheets sheets = excelapp.worksheets; // <-- important part worksheet sheet = sheets.open(...); ... marshal.releasecomobject(sheets); marshal.releasecomobject(sheet);
Comments
Post a Comment