2013-02-19 50 views
6

我正在使用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分鐘後,再次執行。

回答

6

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分鐘,則執行過程將正常進行。

4

我想更簡單的方法就是使用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

相關問題