删除所有计时器VB.net

时间:2017-04-26 11:39:36

标签: vb.net timer

我在课堂上创建计时器

Dim timer As New Timer
                timer.Enabled = True
                timer.Interval = 1000
                timer.Tag = "TimeslipTimer_" & timeslip.id
                AddHandler timer.Tick, AddressOf GlobalTimerTick
                timer.Start()

我遇到的问题是,如果需要,我该如何删除它们?

目前我正在寻找将计时器添加到列表中,类似于下面,但我没有成功

dim timers as new list(of Timer)

For Each c As Timer In Timers
                c.Dispose()
                Timers.Remove(c)
            Next

1 个答案:

答案 0 :(得分:1)

从列表中删除时,必须以相反的顺序访问列表。还记得删除处理程序。

Public Class Form1

    Private WithEvents timer As Timer
    Private timers As New List(Of Timer)

    Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        timer = New Timer
        timers.Add(timer)
        timer.Enabled = True
        timer.Interval = 1000
        'timer.Tag = "TimeslipTimer_" & timeslip.id
        AddHandler timer.Tick, AddressOf GlobalTimerTick
        timer.Start()
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        For x As Integer = timers.Count - 1 To 0 Step -1
            Dim t As Timer = timers(x)
            RemoveHandler t.Tick, AddressOf GlobalTimerTick
            t.Stop()
            t.Dispose()
            timers.RemoveAt(x)
        Next
    End Sub

    Private Sub GlobalTimerTick(sender As Object, e As EventArgs)
        Debug.WriteLine("TICK")
    End Sub
End Class