Post

Using COM? ReleaseComObject is your friend.

If you are using COM Interop from your .NET application, you really need to review the System.Runtime.InteropServices.Marshal.ReleaseComObject method.  Although setting COM object to Nothing would seem like the logical thing to do, the problem is that it could literally take forever (or at least until you exit your application) until the COM reference usage count actually gets decremented; thus actually clearing the COM reference.  So instead of doing the following:

1
comObject = Nothing

Do this:

1
2
3
4
5
6
7
If Not comObject Is Nothing Then
  Do
    If System.Runtime.InteropServices.Marshal.ReleaseComObject(comObject) = 0 Then
      Exit Do
    End If
  Loop
End If

This will cause the object to decrement it’s COM reference count, thus actually releasing it from memory.  I believe that this will eventually occur if you set the object to Nothing, however, because you can’t really control when this will occur (non-deterministic) it’s possible that you will have very undesired results.  The problem with letting the GC handle this is that many COM objects lock some type of resource and therefore, until the garbage collection frees the COM object, you can’t access that resource.  Using ReleaseComObject guarantees that the COM object is removed in a deterministic manner.

UPDATE: I should add that this functionality should be used with extreme care.  Anytime you use methods that are within the System.Runtime.InteropServices.Marshal namespace and especially when bypassing the Garbage Collector, you are removing yourself from the safety net that .NET provides.  Make sure you understand what is occurring and test your application thoroughly.

Also, take the advice of Mattias Sjögren and read what Chris Brumme has to say on this subject.  He explains in much greater detail what this method is for, more than even the documentation goes into… along with the when and when not to use ReleaseComObject.

This post is licensed under CC BY 4.0 by the author.