Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I'm a tad confused - at the end of <code>RunMeFirst</code> you exit the process, so is <code>RunMeSecond</code> run in a different process from the first method or the same process?</p> <p>Either way I would change your code so that <code>xlsWb</code> is scoped locally and just do the following:</p> <pre><code>public void RunMeFirst() { System.Type oSEType = Type.GetTypeFromProgID("Excel.Application"); xlsApp = Activator.CreateInstance(oSEType); Workbook xlsWb = xlsApp.Workbooks.Open("C:\\test1.xls"); // Do stuff xlsWb.Close(false); System.Environment.Exit(0); } </code></pre> <p>You shouldn't really call any of the <code>ReleaseComObject</code> methods except in certain circumstances (for example in server applications where many COM objects will all be in use and so it is critical to release objects as soon as possible). The usual mechanism for cleaning up COM object should simply be to let them go out of scope, in which case the COM object will be released using the same magic the GC uses (I believe that it is cleaned up as the finalizer is run, but I'm not 100% sure on this).</p> <p>The reason why its a good idea to scope <code>xlsWb</code> locally (rather than as a class member or a static member) is that class members will only be cleaned up when the class is cleaned up, and static members are <em>never</em> cleaned up until the appdomain is unloaded. If you do need to clean up a COM object referenced by a static field then the way to do this is to set the static field to <code>null</code> so the underlying COM object can be cleaned up by the GC scoping rules:</p> <pre><code>xlsWb = null; </code></pre> <p>Also there should be no real need to call <code>GC.Collect</code> for similar reasons - Mike Rosenblum gives a fair explanation as to why he's calling <code>GC.Collect</code> and <code>ReleaseComObject</code>, but no real justification as to why he isn't just satisfied with letting the garbage collector do its job. Like I said, there are situations where you might want more control over the release of COM objects, however these are the exception not the rule.</p> <p>You may also find reading <a href="http://blogs.msdn.com/b/visualstudio/archive/2010/03/01/marshal-releasecomobject-considered-dangerous.aspx" rel="nofollow">Marshal.ReleaseComObject Considered Dangerous</a> useful.</p>
 

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