我可以在终结器中调用 Marshall.ReleaseComObject 吗?

Can I call Marshall.ReleaseComObject in a Finalizer?

我在我们的代码库中发现这样的代码:

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

因为 comObject 实际上是一个 .Net 对象(一个 RCW,对吧?)从终结器调用它安全吗?

难不成已经发布了?

正如Hans Passant所说:

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

所以调用必须在if(处理)里面。