Search code examples
c#.netdisposefinalizer

Can I call Marshall.ReleaseComObject in a Finalizer?


I have found on our code base code like this:

if (disposing)
{
    ....
}
Marshal.ReleaseComObject(comObject)

As the comObject is in fact a .Net object (a RCW, right?) is it safe to call it from the Finalizer?

Is it possible that it has been already released?


Solution

  • As Hans Passant said:

    No, that is not safe, an RCW already has its own finalizer. Which first of all makes the code completely unnecessary. More severely, since finalization order is not deterministic you might be calling ReleaseComObject() on an object that is already destroyed

    So the call must be inside the if (disposing).