加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 04:23:19 所属栏目:百科 来源:网络整理
导读:我正在使用C#和xaml构建一个 Windows应用商店应用.我需要在一定的时间间隔后刷新数据(从服务器获取新数据).我使用ThreadPoolTimer定期执行刷新功能,如下所示: TimeSpan period = TimeSpan.FromMinutes(15); ThreadPoolTimer PeriodicTimer = ThreadPoolTime
我正在使用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,period);

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读