使用Excel Interop时InvalidComObjectException [英] InvalidComObjectException when using Excel Interop
问题描述
在我关闭我的应用程序后,我得到一个InvalidComObjectException在下面的代码片段:
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;
}
}
为什么?我不应该使用finalizer来处理COM对象吗?
Why is that? Shouldn't I use finalizers to dispose COM-objects?
推荐答案
Finalizer不处理对象。 Excel.Application接口没有Dispose方法。问题是RCW的终结器在你的终结器运行时已经运行。这是按设计,finalizer的顺序不是确定性的。
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已经自动退出。这是由RCW的终结者做的。不帮助。如果你想要帮助反正写如下:
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();
}
}
类的客户端必须调用Dispose )方法。
The client of your class has to call that Dispose() method.
这篇关于使用Excel Interop时InvalidComObjectException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!