c# - How to clean up COM references in .NET when app will be left running? -


i working on .net program starts new instance of excel, work, ends, must leave excel running. later, when program runs again, attempt hook previous instance.

what best way handle releasing of com objects in situation? if not "releasecomobject" on app object first time, on second run active object, release com object, have memory leak?

the following simplified code illustrates trying do:

private microsoft.office.interop.excel.application xlsapp; private microsoft.office.interop.excel.workbook xlswb;  public void runmefirst() {     //start new instance     system.type osetype = type.gettypefromprogid("excel.application");     xlsapp = activator.createinstance(osetype);     xlswb = xlsapp.workbooks.open("c:\\test1.xls");      //do stuff      xlswb.close(false);     cleanup(ref xlswb);      //do not quit excel here     //no cleanup of xlsapp here?  ok?      system.environment.exit(0); }  public void runmesecond() {     //hook existing instance     xlsapp = marshal.getactiveobject("excel.application");     xlswb = xlsapp.workbooks.open("c:\\test2.xls");      //do stuff      xlswb.close(false);     cleanup(ref xlswb);      xlsapp.quit();     cleanup(ref xlsapp);      system.environment.exit(0); }  public void cleanup(ref object theobj) {     gc.collect();     gc.waitforpendingfinalizers();     gc.collect();     gc.waitforpendingfinalizers();      marshal.finalreleasecomobject(theobj);     theobj = null; } 

thanks

in general, when working office pias, i've found these sorts of problems objects not being released arise when have instance variables hold com objects. in case, these xlsapp , xlswb. don't have quit excel application in order release objects, do have perform following cleanup procedure:

marshal.finalreleasecomobject(xlswb); xlswb = null;  marshal.finalreleasecomobject(xlsapp); xlsapp = null;  gc.collect(); 

local-scoped variables containing com objects don't seem cause problem, instance variables. hope helps!


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -