Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a timer create a new thread?

        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?

like image 312
syncis Avatar asked Mar 05 '11 16:03

syncis


2 Answers

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.

like image 79
David Heffernan Avatar answered Oct 20 '22 04:10

David Heffernan


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.

like image 44
Jim Mischel Avatar answered Oct 20 '22 05:10

Jim Mischel