Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to clean up COM references in .NET when app will be left running?
    primarykey
    data
    text
    <p>I am working on a .NET program that starts a new instance of Excel, does some work, then ends, but must leave Excel running. Later, when the program runs again, it will attempt to hook into the previous instance.</p> <p>What is the best way to handle the releasing of COM objects in this situation? If I do not do a "ReleaseComObject" on the app object the first time, then on the second run get the active object, then finally release the com object, do I have a memory leak?</p> <p>The following simplified code illustrates what I am trying to do:</p> <pre><code>private Microsoft.Office.Interop.Excel.Application xlsApp; private Microsoft.Office.Interop.Excel.Workbook xlsWb; public void RunMeFirst() { //Start a new instance System.Type oSEType = Type.GetTypeFromProgID("Excel.Application"); xlsApp = Activator.CreateInstance(oSEType); xlsWb = xlsApp.Workbooks.Open("C:\\test1.xls"); //Do some stuff xlsWb.Close(false); Cleanup(ref xlsWb); //Do not quit Excel here //No Cleanup of xlsApp here? Is this OK? System.Environment.Exit(0); } public void RunMeSecond() { //Hook into existing instance xlsApp = Marshal.GetActiveObject("Excel.Application"); xlsWb = xlsApp.Workbooks.Open("C:\\test2.xls"); //Do some 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; } </code></pre> <p>Thanks</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload