2012-01-12 38 views
0

我試圖創建一個應用程序,它將從Web API中獲取數據並顯示它,然後每隔5秒左右不斷刷新數據,但我不知道這樣做的最佳方式。我的第一個想法只是一個簡單的計時器,就像this question做的一樣,但我擔心我可能會搞砸了,並讓計時器繼續在後臺運行,當它不應該(如如果用戶離開頁面)。我擔心一些不會發生的事情嗎?這是一個很好的方式去做我想做的事,或者是否有更高效/安全的方式來做到這一點?在Windows Phone中持續更新數據的最佳方法?

回答

2

當您在應用程序外導航時,定時器將不會繼續,但當您導航到應用程序中的另一個頁面時,定時器將繼續。您可以阻止它這樣說:

System.Windows.Threading.DispatcherTimer dt; 

    public MainPage() 
    { 
     InitializeComponent(); 
     dt = new System.Windows.Threading.DispatcherTimer(); 
     dt.Interval = new TimeSpan(0, 0, 0, 0, 1000); // 1000 Milliseconds 
     dt.Tick += new EventHandler(dt_Tick); 
    } 

    protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e) 
    { 
     dt.Stop(); 
    } 

    protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) 
    { 
     dt.Start(); 
    } 

    void dt_Tick(object sender, EventArgs e) 
    { 
     listBox1.Items.Add(listBox1.Items.Count + 1); // for testing 
    } 

    private void PageTitle_Tap(object sender, GestureEventArgs e) 
    { 
     NavigationService.Navigate(new Uri("/Page1.xaml", UriKind.Relative)); // for testing 
    } 

此外,如果你只是檢查大部分時間沒有改變,請考慮使用push notifications數據。

相關問題