我是否需要释放 COM Interop 对象的内部对象?
我有一个使用 COM 的托管类,如下所示。
Public Class MyClass
Private myobj as SomeComObject
Public Sub New()
myobj = CreateObject("SomeComObject.Class")
End Sub
Public Sub DoSomething()
dim innerobj as SomComObject.InnerClass
innerobj = myobj.CreateInnerClass("arg1", true, 5)
innerobj.DoSomething()
End Sub
End Class
由于我通过 COM-Interob dll 使用非托管 dll,我想知道是否需要手动释放 innerobj,或者如果我调用 ReleaseObject(),gc 是否足够聪明,可以自动执行此操作。
我的类实现了 IDisposable,并且我执行以下 atm :
Runtime.InteropServices.Marshal.ReleaseComObject(myobj)
我是否需要释放 COM 对象创建的所有内部对象?如果我必须这样做,顺序重要吗(先内部然后父与父然后内部)?
I have a managed class that uses a COM that looks like this.
Public Class MyClass
Private myobj as SomeComObject
Public Sub New()
myobj = CreateObject("SomeComObject.Class")
End Sub
Public Sub DoSomething()
dim innerobj as SomComObject.InnerClass
innerobj = myobj.CreateInnerClass("arg1", true, 5)
innerobj.DoSomething()
End Sub
End Class
Since I am using an unmanaged dll through a COM-Interob dll I am wondering if I need free the innerobj manually or if the gc is smart enough to do it automagically if I call ReleaseObject()
My class implements IDisposable and I do the following atm:
Runtime.InteropServices.Marshal.ReleaseComObject(myobj)
Do I need to take care of releasing all inner objects that are created by the COM Object or not? And If I do have to do it, does the order matter (first inner then parent vs parent then inner)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我相当确定您应该将它们全部单独发布。至少在使用 Office 自动化时,当您不释放所有内部对象时,这是事情卡在内存中的常见原因,这在有如此多集合的 Office 中很容易做到。
我假设其他 COM 对象也是如此。
I'm fairly certain that you should release them all separately. At least when using Office Automation it's a common reason for things to get stuck in memory when you don't release all the inner objects which is very easy to do in Office where there are so many collections.
I'd assume that it would be the same for other COM objects.
COM 不会释放内部对象。它是一个对象的实例,该对象的类恰好属于另一个类。除非外部对象 (
myObj
) 中有显式代码来保留所创建的内部对象(在调用CreateInnerClass
中创建)的句柄,否则 COM 不知道释放它。myObj
类型中可能有代码可以执行此操作,但这并不典型。COM will not Release the inner object. It is an instantiation of an object whose class happens to belong to another class. Unless there is explicit code in the outer object (
myObj
) to keep a handle to the created inner object (created in the callCreateInnerClass
), COM doesn't know to free it. There could be code in themyObj
type to do this, but that's not typical.