I have a Form named Form1 which contains an object Tim of the Timer class. Unlike the System.Windows.Forms.Timer object, the Timer class (FullName: System.Timers.Timer) raises the Elapsed event on a seperate thread. I think the Timer object does the same thing but synchronizes the event by raising it on the same thread as that of the Form it is in.
When I try to execute the following code, an exception: Cross threaded operation not valid is thrown.
CODE
Public Class Form1
Dim Tim As New System.Timers.Timer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Tim.Interval = 1000
AddHandler Tim.Elapsed, AddressOf Tim_Elapsed
Tim.Enabled = True
End Sub
Sub Tim_Elapsed(ByVal Sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
Me.Text = "The Clock Just Ticked" ' This Line Causes the Exception
End Sub
End Class
Dim Tim As New System.Timers.Timer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Tim.Interval = 1000
AddHandler Tim.Elapsed, AddressOf Tim_Elapsed
Tim.Enabled = True
End Sub
Sub Tim_Elapsed(ByVal Sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
Me.Text = "The Clock Just Ticked" ' This Line Causes the Exception
End Sub
End Class
This is because the Tim_Elapsed method is being invoked on a seperate thread, the one belonging to the object Tim. So, I used the mechanism stated in MSDN and came up with the following code:-
CODE
Public Class Form1
Dim Tim As New System.Timers.Timer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Tim.Interval = 1000
AddHandler Tim.Elapsed, AddressOf Tim_Elapsed
Tim.Enabled = True
End Sub
Sub Tim_Elapsed(ByVal Sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
Dim D As New MyDelegate(AddressOf MyMethod)
Me.Invoke(D)
End Sub
Delegate Sub MyDelegate()
Sub MyMethod()
Me.Text = "The Clock Just Ticked"
End Sub
End Class
Dim Tim As New System.Timers.Timer
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Tim.Interval = 1000
AddHandler Tim.Elapsed, AddressOf Tim_Elapsed
Tim.Enabled = True
End Sub
Sub Tim_Elapsed(ByVal Sender As Object, ByVal e As System.Timers.ElapsedEventArgs)
Dim D As New MyDelegate(AddressOf MyMethod)
Me.Invoke(D)
End Sub
Delegate Sub MyDelegate()
Sub MyMethod()
Me.Text = "The Clock Just Ticked"
End Sub
End Class
All things seem to be fine, but when the delegate method raises an exception, say an overflow exception, the exception is traced on the line which invokes this method rather than the line which raises the exception - I = I / 0.
CODE
Sub MyMethod()
Dim I As Integer = 5
I = I / 0 ' The culprit Line
Me.Text = "The Clock Just Ticked"
End Sub
Dim I As Integer = 5
I = I / 0 ' The culprit Line
Me.Text = "The Clock Just Ticked"
End Sub

This problem raises havoc when trying to debug larger implementation of this concept. Any ideas on how to solve this problem?

