Problems with timer-object

N

Nijazi Halimaji

Hi everybody

I have created a new timer object
WithEvents tmr_check As New System.Timers.Timer

On my form_Load-Event I activated the timer...

Then I made a label on my form and putted on the Elapsed-Event of my timer
object following code to change the Label.Text
Label1.Text = "Ola"

When this event is executed, following error occurs:
"Cross-thread operation not valid: Control 'Label1' accessed from a thread
other than the thread it was created on."

I know that I have to set the label.text on the right thread, but how to do?
Never did this before!

Thanks for every help

Nijazi Halimaji
 
H

Herfried K. Wagner [MVP]

Nijazi Halimaji said:
I have created a new timer object
WithEvents tmr_check As New System.Timers.Timer

On my form_Load-Event I activated the timer...

Then I made a label on my form and putted on the Elapsed-Event of my timer
object following code to change the Label.Text
Label1.Text = "Ola"

When this event is executed, following error occurs:
"Cross-thread operation not valid: Control 'Label1' accessed from a thread
other than the thread it was created on."

'System.Timers.Timer' runs on another thread than the applications UI does.
Instance members of Windows Forms controls are not safe for multithreading,
and thus you cannot access them directly from another thread.
'System.Timers.Timer' has a 'SynchronizingObject' property. If you set this
property to your form, the problem should be solved. Note that
'System.Windows.Forms.Timer' has been designed especially for use in Windows
Forms applications. Maybe this is the better choice in this situation.
 
G

Guest

I have read that using the Windows.Timer doesn't fire exactly at the specific
timer intervals you set because of Windows being busy processing something
else when the timer times out for the event. However, the System.Timer runs
in a separate thread and fires the Elasped event in a more predicatble
manner...is this true?

I tried to convert to Systems Timer but had problems with threads getting
mixed up so glad to hear about the SynchronizingObject. Thanks.
 
H

Herfried K. Wagner [MVP]

Dennis said:
I have read that using the Windows.Timer doesn't fire exactly at the
specific
timer intervals you set because of Windows being busy processing something
else when the timer times out for the event. However, the System.Timer
runs
in a separate thread and fires the Elasped event in a more predicatble
manner...is this true?

Yes, that's true. The "Remarks" section of the documentation for
'System.Timers.Timer' says:

| Server timers can move among threads to handle the
| raised 'Elapsed' event, resulting in more accuracy than
| Windows timers in raising the event on time.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top