Does a timer create a new thread?

后端 未结 2 757
遥遥无期
遥遥无期 2020-12-16 17:35
        timer.Interval = 5000;
        timer.Tick += new EventHandler(timer_Tick);
        timer.Start();

Does \"timer_Tick\" method start in a new

2条回答
  •  青春惊慌失措
    2020-12-16 18:10

    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.

提交回复
热议问题