Using a timer to update the UI Thread

November 27, 2015

In trying to write a Windows 10 Desktop application that refreshes an image on the screen within a timer; I had the following code:



                \_timer = new Timer((data) =>
                {
                    if (\_imgIdx > Images.Count)
                        \_imgIdx = 0;
                    AnimatedImage = Images.ElementAt(\_imgIdx);
                    \_imgIdx++;
                }, null, 0, 300);


However, when I run this, I get an exception:

The application called an interface that was marshalled for a different thread. (Exception from HRESULT: 0x8001010E (RPC_E_WRONG_THREAD))

My assumption was that the update was occurring on a different thread from the UI (a valid assumption I believe); so I, initially tried to call:



var dispatcher = Windows.UI.Core.CoreWindow.GetForCurrentThread().Dispatcher;

However, this gave me a null exception.

DispatcherTimer

The answer is the DispatcherTimer class. Here’s how it’s used:



                \_dispatcherTimer = new DispatcherTimer();
                \_dispatcherTimer.Interval = new TimeSpan(0, 0, 0, 0, 500);
                \_dispatcherTimer.Tick += Dt\_Tick;
                \_dispatcherTimer.Start();

Dt_Tick can now update the UI thread.




        private void Dt\_Tick(object sender, object e)
        {

From the naming convention, you might infer that _dispatcherTimer is a class level variable; that’s because it is. The reason is that you can stop the timer elsewhere in the code:



                \_dispatcherTimer.Stop();



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2022