如何敲定/销毁类变量

时间:2016-04-02 15:15:52

标签: vb.net ole

我有一个程序使用某种Ole连接来建立与Cam / cad软件Powershape的连接。它使用类变量与powershape建立连接,其属性包含有关模型打开的信息。

问题是此连接仅在类变量完成或超出范围时结束。

Dim powershapeRoot As New PSAutomation(Delcam.ProductInterface.InstanceReuse.UseExistingInstance)

这在Subs内部工作正常,因为它超出了范围,但是当你需要来自powershape的数据时,这个程序要求你多次这样做,并且每次重新建立连接可能需要一些时间。因此,您可以将其设为全局变量,因此您只需要连接一次。

Dim powershapeRoot As New PSAutomation(Delcam.ProductInterface.InstanceReuse.UseExistingInstance)
Powershapeglobal = powershapeRoot

但是现在一旦程序关闭,变量就会超出范围。我试着用:

Powershapeglobal.dispose
Powershapeglobal = nothing

这些没有帮助,连接似乎仍然存在,因为变量仍然存在?你如何破坏变量?

1 个答案:

答案 0 :(得分:0)

在.NET中,当.NET变量超出范围时,不会销毁非托管资源。当垃圾收集器将它们从内存中删除时,它们就会被销毁,这就是垃圾收集器认为必要的时候。这称为“非确定性终结”,因为您,开发人员无法确定对象最终确定的确切时刻。

要确保在完成外部资源时清除它们,请调用相关对象的Dispose()方法:

  Dim powershapeRoot As New PSAutomation(Delcam.ProductInterface.InstanceReuse.UseExistingInstance)

并且,当您想要释放连接时:

  powershapeRoot.Dispose();

或者,要自动执行Dispose,请使用.NET“Using”语句:

 Using powershapeRoot As New PSAutomation(Delcam.ProductInterface.InstanceReuse.UseExistingInstance)



 End Using ' Dispose is called automatically here

现在,对于COM对象,该过程还有另一个步骤,您必须显式调用ReleaseComObject()方法,如下所示:

 System.Marshall.ReleaseComObject(powershapeRoot);

然后调用Dispose()。但是,只有在明确引用COM程序集时才需要这样做。使用OleDB连接,调用Dispose就足够了。

https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.marshal.releasecomobject(v=vs.110).aspx

相关问题