views:

10

answers:

1

I get an InvalidComObjectException after I close my application in the following piece of code:

class MyExcelManager
{
  myExelAppInstance = new Excel.Application();

  // finalizer
  ~MyExcelManager()
  {
    myExelAppInstance.Quit(); // InvalidComObjectException thrown here
    myExelAppInstance = null;
  }
}

Why is that? Shouldn't I use finalizers to dispose COM-objects?

+1  A: 

Finalizers do not dispose objects. The Excel.Application interface doesn't have a Dispose method anyway. The problem is that the finalizer for the RCW has already run by the time your finalizer runs. That's by design, the order of finalizers isn't deterministic.

Excel already quits automatically when all of the outstanding interfaces are released. Which is done by the finalizers for the RCWs. Don't help. If you want to help anyway then write it like this:

class MyExcelManager : IDisposable
{
  void Dispose()
  {
    myExelAppInstance.Quit();
  }
}

The client of your class has to call that Dispose() method.

Hans Passant