Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
727 views
in Technique[技术] by (71.8m points)

c# - Executing a function periodically after the function completes its task

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.

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

Step 2 : Refresh function completes its execution

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...