释放COM对象

时间:2019-03-06 10:04:32

标签: vb.net com

我正在从Word插件中调用COM对象。

一点之后,我想关闭我的COM对象并返回到Word。我的问题是,我的COM对象(另一个应用程序的Import表单)一直处于打开状态。当我尝试手动关闭它时,出现以下错误:

https://i.stack.imgur.com/xdvGt.png

我的代码:

   Private Sub save_Click(sender As Object, e As RibbonControlEventArgs) Handles save.Click
    Dim importer = GetObject("", "IMPORT.Application")
    Dim dictionary As Dictionary(Of Integer, String)
    Dim doc As Document = Globals.ThisAddIn.Application.ActiveDocument
    Try
        'Doing some stuff...

        importer.SetWindowVisible(False)
        doc.Close(False)

    Catch ex As Exception
        MessageBox.Show(ex.message)
    Finally
        GC.Collect()
        GC.WaitForPendingFinalizers()
        System.Runtime.InteropServices.Marshal.ReleaseComObject(importer)
        importer = Nothing
    End Try
End Sub

他们在网上各处解释,我必须使用以下命令来释放COM对象:

System.Runtime.InteropServices.Marshal.ReleaseComObject(importer)

在我看来,它似乎不起作用。有人知道为什么吗?

是否可以在我的代码末尾获取我的COM应用程序的processID以便杀死它?

//编辑

所以我尝试在finally语句中调用myOtherMethod()(importer现在是一个类变量)。我什么也没做。什么都没改变。

Private Sub myOtherMethod()
    GC.WaitForPendingFinalizers()
    System.Runtime.InteropServices.Marshal.ReleaseComObject(importer)
End Sub

2 个答案:

答案 0 :(得分:0)

您有COM对象泄漏。指向COM对象的智能指针,该指针在代码中的某个位置已存储,而未释放。您应该释放该指针的所有实例。

答案 1 :(得分:0)

启动IMPORT.Application,使用它,但永远不会终止它。您的IMPORT.Application应该具有可以用来终止它的方法。然后,外接程序中的以下调用将正确释放它。

' Quit instance.
importer.Quit()
System.Runtime.InteropServices.Marshal.ReleaseComObject(importer)
importer = Nothing
' Could be useful to uncomment these lines for debugging purpose. You would be able
' to see whether the importer instance is released when GC runs.
' In production code, never call the Garbage Collector though.
'System.Threading.Thread.Sleep(50)
'System.GC.Collect()
'System.GC.WaitForPendingFinalizers()