Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Firstly, I agree with those that suggest having a finalizer as a backup, but try to avoid it ever being called by explicitly calling myClass.Dispose or through 'using'.</p> <p>e.g.</p> <pre><code>var myClass = new MyClass() try { //do stuff } finally { myClass.Dispose(); } </code></pre> <p>or</p> <pre><code>using (var myClass = new MyClass()) { //do stuff } </code></pre> <p><strong>Marshall.ReleaseComObject</strong></p> <p>If you are using lots of COM objects, I also suggest you use Mashall.ReleaseComObject(comObj) to explicitly clean up references to the RCW.</p> <p>So, the code like this suggested elsewhere:</p> <pre><code>if (comInstance != null) { comInstance.FreeStuff(); comInstance = null; } </code></pre> <p>would become:</p> <pre><code>if (comInstance != null) { comInstance.FreeStuff(); int count = Marshall.ReleaseComObject(comInstance); if (count != 0) { Debug.Assert(false, "comInstance count = " + count); Marshal.FinalReleaseComObject(comInstance); } comInstance = null; } </code></pre> <p>While checking the return value of ReleaseComObject() is not strictly necessary, I like to check it to make sure things are being incremented/decremented as expected.</p> <p><strong>The 2-dot rule</strong></p> <p>If you decide to use this, something to be aware of is that some code may need to be refactored to properly release your COM objects. One in particular is what I call the 2-dot rule. Any line using COM objects that contain 2 dots needs close attention. For example,</p> <pre><code>var name = myComObject.Address.Name; </code></pre> <p>In this statement we get a reference to the Address COM object incrementing its RCW reference count, but we don't have an opportunity to call ReleaseComObject. A better way to do it would be to break it down (try..finally omitted for clarity):</p> <pre><code>var address = myComObject.Address; var name = address.Name; MyReleaseComObject(address); </code></pre> <p>where MyReleaseComObject is a utility method wrapping my count check and FinalReleaseComObject() from above.</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