UWP equivalent of Timer.Elapsed event

I need to fire the event automatically every few minutes. I know that I can do this using the Timers.Elapsed event in Windows Forms applications, as shown 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 a lot of googled and struggling to find what is equivalent to this in UWP.

+5
source share
2 answers

The following code snippet using DispatcherTimer should provide equivalent functionality that performs a callback in the user interface 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 the user interface thread and you only need a timer, you can use ThreadPoolTimer , for example

 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 } } 
+7
source

I recently solved a similar problem when I need periodic timer events in a UWP application.

Even if you use ThreadPoolTimer, you can still make a non-blocking call to the user interface from a timer event handler. This can be achieved by using the Dispatcher object and calling its RunAsync method, for example:

 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); 

Snapshots of code taken from this article: Create a periodic work item .

I hope this will be helpful.

+2
source

Source: https://habr.com/ru/post/1260968/


All Articles