Does the System.Windows.Forms.Timer run on a different thread than the UI?

后端 未结 5 1531
眼角桃花
眼角桃花 2020-12-01 14:24

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

相关标签:
5条回答
  • 2020-12-01 14:35

    No.

    The whole point of a Windows.Forms Timer is that it runs on the GUI Thread.

    Windows (WinForms) runs something called the MessagePump (see Application.Run()) and this is what makes the Timer possible.

    All your code runs as part of an Eventhandler somehow, and a Timer tick will never 'interrupt' any other event handler.

    0 讨论(0)
  • The Windows.Forms timer raises the event back on the UI thread, presumably via the sync-context.

    If you want a non-UI thread, there are other timers - for example System.Timers.Timer or System.Threading.Timer

    0 讨论(0)
  • 2020-12-01 14:43

    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.

    0 讨论(0)
  • 2020-12-01 14:48

    According to the documentation it runs on the main UI thread:

    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.

    0 讨论(0)
  • 2020-12-01 14:53

    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.

    0 讨论(0)
提交回复
热议问题