27

When should I use Marshal.FinalReleaseComObject vs Marshal.ReleaseComObject?

Is there any danger in using Marshal.FinalReleaseComObject?

0

1 Answer 1

29

There's some virtue in FinalReleaseComObject, it will crash your program quicker. "COM object that has been separated from its underlying RCW cannot be used" is the CLR telling you that you taking care of COM reference counts yourself instead of leaving it up the CLR was a mistake. Your mileage may vary, you cannot really trust to get it right when it works on your dev machine. Make sure you implement good error reporting when you deploy the code to your customer's machine.

The virtue is that there's only one place in your code where you got it wrong, the FinalReleaseComObject call. It gets much fuzzier when you use ReleaseComObject. Because that will go undetected for a while, crashing your program when the CLR calls the final IUnknown::Release(), the one that destroys the object. Very far removed from an incorrect ReleaseComObject call. But that's the doomsday scenario, the more likely outcome is that the call just doesn't make any difference because you missed the hard ones. Like mumble["foo"], an indexer reference that is so very hard to see being used.

Well, my advice is obvious: don't do this. You are competing with a machine that never gets it wrong. It is merely a bit slow at doing so. A very good "report from real life" is available here. The "silent assassin" section is most relevant.

If it is absolutely essential to get a COM server to exit instantly then let the machine take care of getting all the reference counts to 0. You do so with GC.Collect(). But do keep in mind that you have to place that call correctly if you want this to also work when you debug. It won't work in the same method that uses the COM objects, explained in this answer. Put it in the calling method instead.

10
  • 2
    Are you suggesting not releasing the object at all?
    – C. Ross
    Commented Oct 14, 2010 at 23:11
  • 3
    Well, maybe that wasn't so clear. Remove all the Marshal class calls. Come back when you notice any difference at all. Commented Oct 14, 2010 at 23:58
  • 5
    I removed all my Marshal class calls and I found the code was much more stable, less RCW and COM errors. +1 Thanks!! I only had them in because the SAP SDK I'm working with said to put 'em in ...
    – Booji Boy
    Commented Jan 21, 2012 at 5:23
  • 3
    @HansPassant does advice (not tu use FinalReleaseCOM) also apply in the situation you are PInvoking unmanaged code? Commented May 30, 2012 at 13:06
  • 3
    No, pinvoke has nothing to do with calling COM interface methods. Pinvoke is done with a [DllImport] attribute, there is no COM interface pointer associated with it. Commented May 30, 2012 at 13:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.