UWP equivalent of Timer.Elapsed event
Asked Answered
K

2

9

I need to fire an event automatically every few minutes. I know I can do this using Timers.Elapsed event in Windows Forms applications as below.

using System.Timers;

namespace TimersDemo
{
    public class Foo
    {
        System.Timers.Timer myTimer = new System.Timers.Timer();

        public void StartTimers()
        {                
            myTimer.Interval = 1;
            myTimer.Elapsed += new System.Timers.ElapsedEventHandler(myTimer_Elapsed);
            myTimer.Start();
        }

        void myTimer_Elapsed(object sender, EventArgs e)
        {
            myTimer.Stop();
            //Execute your repeating task here
            myTimer.Start();
        }
    }
}

I have googled a lot and struggling to find what is the equivalent of this in UWP.

Killer answered 8/12, 2016 at 7:12 Comment(0)
I
12

The following code snippet using a DispatcherTimer should provide equivalent functionality, which runs the callback on the UI thread.

using Windows.UI.Xaml;
public class Foo
{
    DispatcherTimer dispatcherTimer;
    public void StartTimers()
    {
        dispatcherTimer = new DispatcherTimer();
        dispatcherTimer.Tick += dispatcherTimer_Tick;
        dispatcherTimer.Interval = new TimeSpan(0, 0, 1);
    }

    // callback runs on UI thread
    void dispatcherTimer_Tick(object sender, object e)
    {
        // execute repeating task here
    }
}

When there is no need to update on the UI thread and you just need a timer, you can use a ThreadPoolTimer, like so

using Windows.System.Threading;
public class Foo
{
    ThreadPoolTimer timer;

    public void StartTimers()
    {
        timer = ThreadPoolTimer.CreatePeriodicTimer(TimerElapsedHandler, new TimeSpan(0, 0, 1));
    }

    private void TimerElapsedHandler(ThreadPoolTimer timer)
    {
        // execute repeating task here
    }
}
Inconsistency answered 8/12, 2016 at 7:16 Comment(7)
I believe yes, Thank you! However I would request a detailed answer, for other readers, if you can. Otherwise this can be considered a link only answer. Albeit, MSDN is not going anywhere anytime soon, I believe!Killer
@DevrajGadhavi note that DispatcherTimer runs callback on UI thread, so it's not exactly equivalent to System.Timers.Timer.Guth
@Evk, I might actually need it to run on the UI thread. What could be the major drawbacks in doing so? Moreover, any other appropriate alternative will be appreciated, as a separate answer.Killer
@DevrajGadhavi well usual drawbacks - if operation is computationally expensive or blocking - UI will freeze during it.Guth
@Evk, I can live with that as the operation is not that much computational or time consuming. I had thought of it. Thank you for pointing it out though!Killer
@meng, nice addition. I actually need to update on the UI thread, a grid control and a label. I am working on an auto refresh feature that will update the information, after the background thread has synced information from the server.Killer
Remember to add dispatcherTimer.Start();Donate
T
2

Recently I solved the similar task, when I needed periodic timer events in UWP application.

Even you use ThreadPoolTimer, you are still able to make non-blocking call to UI from the timer event handler. It can be achieved by using Dispatcher object and calling its RunAsync method, like this:

TimeSpan period = TimeSpan.FromSeconds(60);

ThreadPoolTimer PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer((source) =>
{
    // 
    // TODO: Work
    // 

    // 
    // Update the UI thread by using the UI core dispatcher.
    // 
    Dispatcher.RunAsync(CoreDispatcherPriority.High,
        () =>
        {
            // 
            // UI components can be accessed within this scope.
            // 

        });

}, period);

The code snippet is taken from this article: Create a periodic work item.

I hope it will be helpful.

Tranquillity answered 9/12, 2016 at 16:31 Comment(3)
I think you should edit your answer and post essential excerpts from the link. That way you would also start earning some reputation.Killer
Thank you guys for your comments, I edited my answer in accordance with your recommendations.Tranquillity
It is recommended to not use the High priority because it is for system events.Hairbreadth

© 2022 - 2024 — McMap. All rights reserved.