oocharlesxx
oocharlesxx

Reputation: 27

C# winform Two timers access same variable

I'm new to C# and I'm doing a project needs two timer to access the same variable at the same time.(one to read and other one to write or update).So, my problem is which Timer should I use? Forms.Timer or Thread.Timer. I've read some article about their difference. Since I want to use these timers to update the Interface of the program (image in picture box), So I think Forms.Timer should be used here since it's related to GUI stuff. However, the order that which timer executes first is also matter, so I think Thread.Timer should also be considered. Is there any way I can combine them together?

Update: I'm doing a ECG project, so basically I'm keeping receiving data and I want to draw them on the form. however, since drawing took about 40 ms, so using one timer would have delay but I need real time.(For example, If I set the interval to 100 ms, then It took 140 ms to finish one frame drawing that should be finished in 100 ms. This will cause 40 ms delay for every tick. ) Therefore, My solution is using one timer to update the data buffer when I received the data, and use other timer to call Invalidate, which would repaint all the new data. Should I use thread.timer to do the updating of data and form.timer to redraw the form?

Upvotes: 1

Views: 269

Answers (1)

VillageTech
VillageTech

Reputation: 1995

The main difference between both timers is that the Form.Timer works in the same thread as your Form, so there is no problem in accessing or changing state of any GUI component (control etc.) by Tick event handler code. In case of Thread.Timer, there is no guarantee that the TimerCallback method is called from current thread (can be, but not must be), so accessing the GUI components can be slightly hard and not easy (you have to use Invoke(), like here: Accessing a form's control from a separate thread). On the other hand, any long-term and intensive processing, implemented in Form.Timer.Tick handler will be executed in same thread as GUI, so it can degrade GUI efficiency and responsibility. So, the general rule is: for fast, short-term operations on GUI components, use Form.Timer, and for long-term, heavy computations, not requiring access to GUI components, use Thread.Timer. Of course, it is simplified rule - the final decision should depend to specific case.

Upvotes: 2

Related Questions