Executing a function periodically after the function completes its task

后端 未结 2 1480
北恋
北恋 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.

提交回复
热议问题