Releasing a COM object reference safely from .NET

3.5k views Asked by At

I have read a lot of articles on the net about releasing RCW's safely, and it seems to me that no one can agree on exactly what needs to be done in what order, so I'm asking you guys for your opinions. For example, one could do this:

object target = null;
try {
    // Instantiate and use the target object.
    // Assume we know what we are doing: the contents of this try block
    // do in fact represent the entire desired lifetime of the COM object,
    // and we are releasing all RCWs in reverse order of acquisition.
} finally {
    if(target != null) {
        Marshal.FinalReleaseComObject(target);
        target = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

However, some people advocate doing the garbage collection before Marshal.FinalReleaseComObject, some after, and some not at all. Is it really necessary to GC every single RCW manually, especially after it has already been detached from its COM object?

To my mind, it would be simpler and easier to just detach the RCW from the COM object and leave the RCW to expire naturally:

object target = null;
try {
    // Same content as above.
} finally {
    if(target != null) {
        Marshal.FinalReleaseComObject(target);
    }
}

Is it sufficient to do that?

1

There are 1 answers

3
Tony Lee On BEST ANSWER

To have your reference to the target COM object released, it is sufficient and preferred to just call Marshal.FinalReleaseComObject and not force a collect. In other words, you've met your responsibility to release your reference as soon as you were done with it. I won't touch the issue of FinalReleaseComObject vs ReleaseComObject.

This leaves the bigger question of why do people advocate calling GC.Collect() and WaitForPendingFinalizers()?

Because for some designs, it's hard to know when there are no more managed references so you can't safely call ReleaseComObject. You have two choices, let the memory build up and hope a collect happens or force a collect. [see Steven Jansen's note in the comments]

An additional note is that setting target to null is usually unnecessary, and specifically is unnecessary in your sample code. Setting objects to nothing is common practice for VB6 since it uses a reference count based garbage collector. The compiler for C# is clever enough (when building for release) to know that target is unreachable after its last use and could be GC'd, even before leaving scope. And by last use, I mean last possible use so there are cases where you might set it to null. You can see this for yourself with the code below:

   using System;
   class GCTest
   {
       ~GCTest() { Console.WriteLine("Finalized"); } 
       static void Main()
       {
           Console.WriteLine("hello");
           GCTest x = new GCTest();
           GC.Collect();
           GC.WaitForPendingFinalizers();
           Console.WriteLine("bye");
       }
   }

If you build release (e.g., CSC GCTest.cs), "Finalized" will print out between "hello" and "bye". If you build debug (e.g., CSC /debug GCTest.cs), "Finalized" will print out after "bye" whereas setting x to null prior to Collect() would have "fixed" that.