2017-04-26 60 views
0

我一類刪除所有計時器VB.net

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

使用LINQ'Timers.ForEach(子(T)RemoveHandler t.Tick,AddressOf GlobalTimerTick:t.Dispose結束分):Timers.Clear()'確保YPU有'進口System.Linq' – Codexer

回答

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