title: VB Thread Timer Update UI
body: <p>I made a small program that allows for individual timer countdowns for each button clicked. (e.g. clicking on button 1 will start a countdown for button 1 whilst updating the text on the button itself to reflect the time remaining.)</p>
  
  <p>My worry now is that I'm not sure how well my program would work in the long run. Here's a snippet of the code.</p>
  
  <pre><code> Private Sub depBtn_Clicked(sender As Button, e As EventArgs)
      If sender.BackColor = Color.Green Then
          Dim depRow() As Data.DataRow
          Dim id As String = sender.Name
          depRow = DepartmentDataSet.Departments.Select("ID Like '" &amp; id &amp; "'")          
          sender.BackColor = Color.Red
  
          Dim timerBtn As New DepartmentTimer(sender, depRow(0)("Duration"), depRow(0)("ID"))
  
          Dim TimerDelegate As New System.Threading.TimerCallback(AddressOf TimerTask)
          Dim TimerItem As New System.Threading.Timer(TimerDelegate, timerBtn, 0, 1000)
          timerBtn.timerRef = TimerItem
      End If
  End Sub
  
  Private Delegate Sub TimerTaskDelegate(ByVal obj As Object)
  
  Private Sub TimerTask(ByVal obj As Object)
      If Me.InvokeRequired() Then
          Me.Invoke(New TimerTaskDelegate(AddressOf TimerTask), obj)
      Else
          Dim depTimer As DepartmentTimer = DirectCast(obj, DepartmentTimer)
          depTimer.countDown()
  
          If depTimer.duration = -1 Then
              depTimer.finish()
              depTimer.timerRef.Dispose()
          End If
      End If
  End Sub
  </code></pre>
  
  <p>I have read and also experienced that if I were to update on the UI thread directly from the timer callback the whole program would crash. So I ended up using a delegate in accordance to here <a href="http://tech.xster.net/tips/invoke-ui-changes-across-threads-on-vb-net/" rel="nofollow">http://tech.xster.net/tips/invoke-ui-changes-across-threads-on-vb-net/</a>.</p>
  
  <p>Is this a proper way of doing it or am I doing anything redundant/inefficient?
  Also when I dispose of the Timer object. How would I go about cleaning up the DepartmentTimer class instance (timerBtn)? The button can be activated again once the timer runs out so I'm afraid that the instances would build up if I don't take care of them properly.</p>
  
  <p>Thanks in advance for any help.</p>