Executing a function periodically after the function completes its task

后端 未结 2 1474
北恋
北恋 2020-12-20 20:48

I am building a windows store app using C# and xaml. I need to refresh the data after certain interval of time (bring the new data from the server). I used ThreadPoolTimer t

相关标签:
2条回答
  • 2020-12-20 21:20

    I think an easier way to do this is with 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 a Task which can be used to detect errors.

    0 讨论(0)
  • 2020-12-20 21:24

    The AutoResetEvent will solve this problem. Declare a class-level AutoResetEvent instance.

    AutoResetEvent _refreshWaiter = new AutoResetEvent(true);
    

    Then inside your code: 1. wait on it till it is signaled, and 2. pass its reference as an argument to 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 dp.RefreshAsync method, call _refreshWaiter.Set(); so that if 15 seconds have passed then the next RefreshAsync may be called. Note that if RefreshAsync method takes less than 15 minutes, the execution proceeds as normal.

    0 讨论(0)
提交回复
热议问题