views:

39

answers:

1

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

Is there any danger in using Marshal.FinalReleaseComObject?

+3  A: 

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.

Hans Passant
Are you suggesting not releasing the object at all?
C. Ross
Yes. Why do you think you have to?
Hans Passant
@Hans Our vendor specified in their documentation that you had to release all objects after using them.
C. Ross
Yes you do. *Really* important when you write C++ code. The kind of code they wrote. C++ programmers spend a lot of time worrying about that. Well, debugging their memory leaks. The notion of automatic memory management is a pretty alien to them, you can't trust a machine to get *that* right when it took you 5+ years to stop writing leaky code.
Hans Passant
Well, maybe that wasn't so clear. Remove all the Marshal class calls. Come back when you notice any difference at all.
Hans Passant