C# – Does a timer create a new thread

c++multithreadingtimer

        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?

Best Solution

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.