在函数完成任务后定期执行函数

本文关键字:函数 执行 完成任务 | 更新日期: 2023-09-27 17:59:56

我正在使用C#和xaml构建一个windows商店应用程序。我需要在一定的时间间隔后刷新数据(从服务器中获取新数据)。我使用ThreadPoolTimer定期执行刷新功能,如下所示:

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

这工作正常。唯一的问题是刷新函数在下一个实例提交到线程池之前没有完成。是否有某种方法可以指定其执行之间的间隔。

步骤1:刷新功能执行(需要任何时间)

步骤2:刷新功能完成其执行

步骤3:间隔15分钟,然后进入步骤1

执行刷新功能。执行结束15分钟后,它再次执行。

在函数完成任务后定期执行函数

AutoResetEvent将解决此问题。声明类级别的AutoResetEvent实例。

AutoResetEvent _refreshWaiter = new AutoResetEvent(true);

然后在你的代码里:1。等待它,直到它被发出信号,以及2。将其引用作为参数传递给RefreshAsync方法。

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

最后,在dp.RefreshAsync方法结束时,调用_refreshWaiter.Set();,这样,如果已经过了15秒,则可以调用下一个RefreshAsync。请注意,如果RefreshAsync方法花费的时间少于15分钟,则执行将照常进行。

我认为一种更简单的方法是使用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);

该解决方案还提供了可用于检测错误的Task