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.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Devraj Gadhavi
  • 3,541
  • 3
  • 38
  • 67

2 Answers2

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
    }
}
meng
  • 441
  • 3
  • 9
  • 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](http://meta.stackexchange.com/q/8231/217907) answer. Albeit, MSDN is not going anywhere anytime soon, I believe! – Devraj Gadhavi Dec 08 '16 at 07:27
  • 1
    @DevrajGadhavi note that DispatcherTimer runs callback on UI thread, so it's not exactly equivalent to System.Timers.Timer. – Evk Dec 08 '16 at 07:40
  • @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. – Devraj Gadhavi Dec 08 '16 at 07:45
  • @DevrajGadhavi well usual drawbacks - if operation is computationally expensive or blocking - UI will freeze during it. – Evk Dec 08 '16 at 07:48
  • @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! – Devraj Gadhavi Dec 08 '16 at 07:53
  • @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. – Devraj Gadhavi Dec 08 '16 at 08:27
  • 1
    Remember to add dispatcherTimer.Start(); – 27k1 Jun 02 '18 at 12:54
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.

ebontrop
  • 31
  • 1
  • 3
  • I think you should edit your answer and post essential excerpts from the link. That way you would also start earning some reputation. – Devraj Gadhavi Dec 10 '16 at 07:54
  • Thank you guys for your comments, I edited my answer in accordance with your recommendations. – ebontrop Dec 10 '16 at 16:35
  • It is [recommended](https://learn.microsoft.com/en-us/uwp/api/windows.ui.core.coredispatcherpriority) to not use the `High` priority because it is for system events. –  May 11 '18 at 15:09