Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/vb.net/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vb.net 类在设置为nothing Visual Basic后仍处于活动状态_Vb.net - Fatal编程技术网

Vb.net 类在设置为nothing Visual Basic后仍处于活动状态

Vb.net 类在设置为nothing Visual Basic后仍处于活动状态,vb.net,Vb.net,我有一个在VisualBasic中没有窗体的类,它包括一个间隔为5000ms的计时器 我遇到的问题是,当我将类设置为Nothing时,类似乎仍处于活动状态,计时器仍在滴答作响 有没有办法彻底处理这个类并结束它的生命 Public Class MyCustomClass Public GlobalTimer As New System.Windows.Forms.Timer Public Sub New() GlobalTimer.Interval = 5000 Gl

我有一个在VisualBasic中没有窗体的类,它包括一个间隔为5000ms的计时器

我遇到的问题是,当我将类设置为Nothing时,类似乎仍处于活动状态,计时器仍在滴答作响

有没有办法彻底处理这个类并结束它的生命

Public Class MyCustomClass

  Public GlobalTimer As New System.Windows.Forms.Timer

  Public Sub New()

    GlobalTimer.Interval = 5000
    GlobalTimer.Enabled = True
    GlobalTimer.Start()
    AddHandler GlobalTimer.Tick, AddressOf GlobalTimer_Tick

  End Sub

  Public Sub GlobalTimer_Tick(ByVal sender As Object, ByVal e As 
  EventArgs)
    Console.WriteLine("Tick")
  End Sub

End Class

的确,“将类实例设置为零并不能清除所有内容。” 鉴于此,下面是MyCustomClass的更新版本,以实现所需的行为。该类现在实现IDisposable接口和Dispose()方法

为了使其工作,您需要调用dispose方法MyCustomClass对象,或者在using块中使用该方法,而不是将其设置为nothing

dim cusClassObj as new MyCustomClass()
    ' perform other tasks here
cusClassObj.Dispose()


另外,请分享您在中使用的示例代码:并尝试阅读。如果您不分享清空类的函数及其结构,我们无法告诉您为什么不清空代码。如果你花时间阅读,你不必像我说的那样把所有代码都放进去:你会看到你需要分享什么来帮助我们帮助你如果你不能分享这个确切的代码,那么就创建一个模仿问题的可共享(例如,去掉任何专有信息等)版本。如果你不能模仿这个问题,那么你需要比较这两个类,看看你在每个类中做的不同。如果你可以模拟这个问题,那么瞧,你已经创建了一个MCVE,你应该在这里共享它,它将允许其他人帮助你。将类实例设置为Nothing并不能清除所有内容。您仍然需要使用.dispose()之类的方法正确地处理实例,并处理事件以停止计时器。此外,垃圾收集仅在需要时调用,而不是每次将某项设置为nothing时调用。您需要在类中使用一个方法,
GlobalTimer.Dispose()
,这样您就可以执行
mycustomclass.Dispose
dim cusClassObj as new MyCustomClass()
    ' perform other tasks here
cusClassObj.Dispose()
Using cusClassObj As New MyCustomClass()
    ' perform other tasks here
End Using