Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UWP equivalent of Timer.Elapsed event

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.

like image 232
Devraj Gadhavi Avatar asked Dec 08 '16 07:12

Devraj Gadhavi


1 Answers

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
    }
}
like image 72
meng Avatar answered Oct 18 '22 05:10

meng