CherryQu
CherryQu

Reputation: 3393

DispatcherTimer.Start() starts the Tick in a background thread?

Does DispatcherTimer start a new thread?

I noticed that the code example below is non-blocking:

//  DispatcherTimer setup
dispatcherTimer = new System.Windows.Threading.DispatcherTimer();
dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);
dispatcherTimer.Interval = new TimeSpan(0,0,1);
dispatcherTimer.Start();

So in this code example, will Tick (i.e. EventHandler) be executed on a different thread or will it be executed on the same thread that is setting up the dispatcherTimer?

Upvotes: 4

Views: 2214

Answers (2)

Peter Duniho
Peter Duniho

Reputation: 70681

The Tick event handler is always raised in the thread that owns the DispatcherTimer object. The normal way to use that timer class is to create the object in the UI thread, and then the event handler will be raised in the UI thread.

But as far as your question about how this happens and whether DispatcherTimer starts a new thread goes…

The exact implementation of the timer is just that: an implementation detail. The framework could use a background thread for timing, or may use some other mechanism.

As it happens, the current implementation of DispatcherTimer uses the native WM_TIMER mechanism (i.e. no, it doesn't start a new thread). Which makes sense, as one feature of DispatcherTimer is to raise the timer event on the dispatcher thread, and a convenient way to do that is to have the timer notification come from Windows in that same thread, which WM_TIMER does.

But you can't and shouldn't assume this. All you really know is that DispatcherTimer promises to raise the timer event in the dispatcher thread.

Note that regardless, the Start() method would necessarily be non-blocking. If that method call blocked, it would negate every benefit of using a timer in the first place. :)

Upvotes: 7

CherryQu
CherryQu

Reputation: 3393

Also worth noting: there are two DispatcherTimer classes!

The first one is System.Windows.Threading.DispatcherTimer. This is the class in my question. As explained in the accepted answer, Tick will be executed on the same thread.

The second one is Windows.UI.Xaml.DispatcherTimer. In the documentation of this class it says:

The DispatcherTimer can be used to run code on the same thread that produces the UI thread. Code running on this thread has the privilege to create and modify objects that can only be created and modified on the UI thread.

So the Windows.UI.Xaml.DispatcherTimer will be setup on a UI thread and its Tick will also be executed on a UI thread!

Upvotes: 1

Related Questions