I have a main thread that creates a form object which creates and sets a timer to run a function named updateStatus() every minute. But updateStatus() is also called by the main thread at several places.
However, I am not clear about whether or not it will cause any synchronization problems. Does the System.Windows.Forms.Timer in C# run on a different thread other than the main thread?
No, a timer runs in the thread in which it was created.
The . NET Framework has full support for running multiple threads at once. In this article, we'll look at how threads accomplish their task and why you need to be careful how you manage a WinForms application with multiple threads. A thread is the basic unit of which an operating system uses to execute code.
No, the timer events are raised on the UI thread.
You won't have any synchronicity problems. This is the correct version of the timer control to use in a WinForms application; it's specifically designed to do what you're asking. It's implemented under the hood using a standard Windows timer.
The documentation confirms this in the Remarks section:
A Timer is used to raise an event at user-defined intervals. This Windows timer is designed for a single-threaded environment where UI threads are used to perform processing. It requires that the user code have a UI message pump available and always operate from the same thread, or marshal the call onto another thread.
When you use this timer, use the Tick event to perform a polling operation or to display a splash screen for a specified period of time. Whenever the Enabled property is set to true and the Interval property is greater than zero, the Tick event is raised at intervals based on the Interval property setting.
No, the timer's Tick event is raised from the UI thread by the message loop when it receives a WM_TIMER message. You're always good with that, it can only run when your UI thread is idle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With