Function execution periodically after task execution

I am building a windows store application using c # and xaml. I need to update the data after a certain period of time (bring new data from the server). I used ThreadPoolTimer to execute my update function periodically as follows:

TimeSpan period = TimeSpan.FromMinutes(15); ThreadPoolTimer PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer(async(source)=> { n++; Debug.WriteLine("hello" + n); await dp.RefreshAsync(); //Function to refresh the data await Dispatcher.RunAsync(CoreDispatcherPriority.High, () => { bv.Text = "timer thread" + n; }); }, period); 

This is working correctly. The only problem is that if the update function does not end before its next instance is sent to the thread pool. Is there a way to indicate the gap between its execution.

Step 1: The update function is running (takes some time)

Step 2: update function completes execution

Step 3: 15 minutes clearance, then go to Step 1

The update function is running. 15 minutes after completion of execution, it is executed again.

+6
source share
2 answers

AutoResetEvent will solve this problem. Declare an instance of the AutoResetEvent class at the class level.

 AutoResetEvent _refreshWaiter = new AutoResetEvent(true); 

Then inside your code: 1. Wait until it is signaled, and 2. pass its link as an argument to the RefreshAsync method.

 TimeSpan period = TimeSpan.FromMinutes(15); ThreadPoolTimer PeriodicTimer = ThreadPoolTimer.CreatePeriodicTimer(async(source)=> { // 1. wait till signaled. execution will block here till _refreshWaiter.Set() is called. _refreshWaiter.WaitOne(); n++; Debug.WriteLine("hello" + n); // 2. pass _refreshWaiter reference as an argument await dp.RefreshAsync(_refreshWaiter); //Function to refresh the data await Dispatcher.RunAsync(CoreDispatcherPriority.High, () => { bv.Text = "timer thread" + n; }); }, period); 

Finally, at the end of the dp.RefreshAsync method dp.RefreshAsync call _refreshWaiter.Set(); so that if 15 seconds have passed, you can call the next RefreshAsync. Note that if the RefreshAsync method takes less than 15 minutes, execution will proceed as usual.

+6
source

I think an easier way to do this is async :

 private async Task PeriodicallyRefreshDataAsync(TimeSpan period) { while (true) { n++; Debug.WriteLine("hello" + n); await dp.RefreshAsync(); //Function to refresh the data bv.Text = "timer thread" + n; await Task.Delay(period); } } TimeSpan period = TimeSpan.FromMinutes(15); Task refreshTask = PeriodicallyRefreshDataAsync(period); 

This solution also provides Task , which can be used to detect errors.

+4
source

All Articles