函数完成其任务后定期执行该函数 [英] Executing a function periodically after the function completes its task

查看:40
本文介绍了函数完成其任务后定期执行该函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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 to execute my refresh 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 properly. The only problem is that what if refresh function doesnot complete before its next instance is submitted to the thread pool. Is there some way to specify the gap between its execution.

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

Step 1 : Refresh function executes (takes any amount of time)

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

Step 2 : Refresh function completes its execution

第3步:间隔15分钟,然后转到第1步

Step 3 : Gap for 15mins then go to Step 1

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

Refresh function executes. 15mins after its execution ends, it executes again.

推荐答案

AutoResetEvent 将解决此问题.声明一个类级别的AutoResetEvent实例.

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

AutoResetEvent _refreshWaiter = new AutoResetEvent(true);

然后在代码内:1.等待它,直到收到信号为止,然后2.将其引用作为参数传递给RefreshAsync方法.

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

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

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.

这篇关于函数完成其任务后定期执行该函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆