Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 main thread at several places.

However, I am not clear about whether or not it will cause any synchronization problems. Does the System.Windows.Forms.Timer in C# run on a different thread other than the main thread?

like image 903
user186246 Avatar asked Apr 17 '11 15:04

user186246


People also ask

Does timer create a new thread?

No, a timer runs in the thread in which it was created.

Is WinForms multithreaded?

The . NET Framework has full support for running multiple threads at once. In this article, we'll look at how threads accomplish their task and why you need to be careful how you manage a WinForms application with multiple threads. A thread is the basic unit of which an operating system uses to execute code.


2 Answers

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.

like image 98
Cody Gray Avatar answered Oct 19 '22 10:10

Cody Gray


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.

like image 30
Hans Passant Avatar answered Oct 19 '22 10:10

Hans Passant