timer.Interval = 5000;
timer.Tick += new EventHandler(timer_Tick);
timer.Start();
Does "timer_Tick" method start in a new thread or is it still in the thread it was created in?
No, a timer runs in the thread in which it was created.
I'm assuming you are talking about System.Windows.Forms.Timer
which is implemented using the thread message loop. Underlying a WinForms timer is the Win32 API SetTimer()
which operates by posting WM_TIMER
messages to the message queue of the thread which SetTimer()
.
One of the consequences of this is that if you have an event handler that takes longer than your timer interval then your timer will not fire at the desired interval. If this was a problem then you'd need to house your timer in another thread.
As a thought experiment, imagine what would happen if your timer event did execute in a different thread. Now you have a synchronisation problem to handle. Your timer event is likely to want to access objects from the other thread. But to do so will result in race conditions.
A timer doesn't really "run". That is, when you start a timer, the operating system creates some data structures that tell it to issue a "tick" periodically--at whatever period you've specified. But it's not like the timer is sitting there spinning, eating CPU resources while it waits for the proper time. All of the .NET timer types and the Windows API timer types work this way.
The difference is in what happens when it comes time to make a tick. As @David Hefferman pointed out, with System.Windows.Forms.Timer
, the Elapsed
event handler is called on the same thread that created the timer. System.Threading.Timer
calls its callback on a thread pool thread. Under the hood, System.Timers.Timer
is called on a pool thread, but you can use the SynchronizingObject
property to raise the Elapsed
event on the UI thread or any other thread.
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