1

I recently switched my code from using the windows.forms.timer to the systems.timer.timer and it has resulted in a multithreading error. I'm using the timer to trigger just one event so multithreading shouldn't be an issue. To give more detail I have implemented the timer at follows: At the top of the class I have:

Private Shared timr1sec As System.Timers.Timer

When the program loads (Private Sub Test_load):

timr1sec = New System.Timers.Timer(1000)
AddHandler timr1sec.Elapsed, AddressOf OnTimedEvent

In OnTimedEvent I call several subroutines, and write some data to the screen using a ListView object. VisualExpress throws the multithreading error on the last line of this code, which is in OnTimedEvent

    Dim itm As New ListViewItem(str(0))

    itm.SubItems.Add(str(1))
    itm.SubItems.Add(str(2))
    itm.SubItems.Add(str(3))
    itm.SubItems.Add(str(4))
    itm.SubItems.Add(str(5))

    ListView1.Items.AddRange(New ListViewItem() {itm})

Any idea what it is about this new timer that's causing VisualExpress to say I'm multithreading?

2

1 Answer 1

3

System.Timers.Timer raises its Elapsed event on a threadpool thread.

You should use a System.Windows.Forms.Timer, which always uses the UI thread.

If you really want to, you could set the SynchronizingObject property on the Timers.Timer to tell it to marshal its events to the UI thread, but there's no point.

Sign up to request clarification or add additional context in comments.

5 Comments

I was using System.Windows.Forms.Timer but I'm using the timer as a stopwatch and as I've found out Windows.Forms.Timer is not designed for this. A nice explanation is here; msdn.microsoft.com/en-us/magazine/cc164015.aspx
I've found a few examples of synchronizingObject but I'm not sure how this applies. Could you tell me more or point me to a good example?
Timers.Timer can call SynchronizingObject.BeginInvoke to run the callback in the UI thread
OK, I've set timr1sec.SynchronizingObject = textbox1 and that synchronized the timer thread with the form. Thanks for your help!
Note that by setting SynchronizingObject, you will lose precision, since you need to wait for the message loop before your handler runs.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.