设置为无Visual Basic后,类仍处于活动状态

时间:2017-05-18 12:30:24

标签: vb.net

我有一个没有Visual Basic基础的类,它包含一个间隔为5000毫秒的计时器。

我遇到的问题是当我将类设置为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

1 个答案:

答案 0 :(得分:1)

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

Public Class MyCustomClass
    Implements IDisposable

    Public GlobalTimer As New System.Windows.Forms.Timer

    Public Sub New()        
        GlobalTimer.Interval = 1000
        GlobalTimer.Enabled = True
        GlobalTimer.Start()
        AddHandler GlobalTimer.Tick, AddressOf GlobalTimer_Tick

    End Sub

    Public Sub Dispose() Implements IDisposable.Dispose
        GlobalTimer.Dispose()
    End Sub

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

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

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

OR

Using cusClassObj As New MyCustomClass()
    ' perform other tasks here
End Using