0

I try to run a timer from my winform application. For some reason the function that should run on the timer's tick (IsTimeOffsetValid) is not called nor stopped on break point, and basically nothing happens. I attached a code sample below.

I appreciate the help.

Module Module1
    Sub main()
        Dim OutputForm As New Form17
        Application.Run(OutputForm)
    End Sub
End Module
Public Class Form17

    Private TimerServerOffset As New System.Timers.Timer

    Private Sub Form17_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        AddHandler TimerServerOffset.Elapsed, New System.Timers.ElapsedEventHandler(AddressOf IsTimeOffsetValid)
        TimerServerOffset.Interval = 1
        TimerServerOffset.Start()
    End Sub

    Private Sub IsTimeOffsetValid()
        MsgBox("IsTimeOffsetValid")
    End Sub

End Class
GSerg
  • 76,472
  • 17
  • 159
  • 346
  • 3
    Your code snippet fails to demonstrate the problem. Displaying a message box in a worker thread such as started by System.Timers.Timer is a Bad Idea. There is no guarantee that the message box will be visible, its window has no Z-order relationship with the window owned by the UI thread. It can easily hide underneath such a window, entirely invisible to the user. Using Control.BeginInvoke() to force UI code to run on the UI thread is *not* optional. – Hans Passant Jul 27 '14 at 09:22
  • 1
    The timer must be `withevents`. Adding a [relaxed delegate handler](http://msdn.microsoft.com/en-us/library/bb531336(v=vs.90).aspx) requires `option strict off` (`Handles` works in any case). – GSerg Jul 27 '14 at 09:25

1 Answers1

3

Apart from errors in the code that you posted there are other issues with the design.

Read this question: System.Timers.Timer vs System.Threading.Timer

The callback is called on a worker thread (not the UI thread) so displaying a message box could be a big problem.

then switch to a more fitting timer. If all you want to do is validate the inputs every second, switch to the System.Windows.Forms.Timer. The tick handler runs on the UI thread so you can change the UI in the handler.

Then consider changing the interval a message box popping up every millisecond is not possible and not user friendly.

Finally, I would suggest NOT using a timer for this: just handle changes to the input fields and respond to changed inputs or use the standard validation events of the WinForms controls. This is much cheaper (on the CPU) and will not mess with the focus.

Community
  • 1
  • 1
Emond
  • 50,210
  • 11
  • 84
  • 115