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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With