【问题标题】:Best way to continously update data in Windows Phone?在 Windows Phone 中持续更新数据的最佳方式?
【发布时间】:2012-01-12 23:37:53
【问题描述】:

我正在尝试创建一个应用程序,该应用程序将从 Web API 获取数据并显示它,然后每 5 秒左右不断刷新数据,但我不知道执行此操作的最佳方法。

我的第一个想法只是一个简单的计时器,就像在this question 中所做的那样,但我担心我可能会把它搞砸并让计时器在不应该的时候继续在后台运行(就像用户离开页面一样)。我是否担心某些实际上不会发生的事情?这是做我想做的事情的好方法,还是有更有效/更安全的方法?

【问题讨论】:

    标签: c# timer windows-phone continuous


    【解决方案1】:

    当您在应用程序外部导航时,计时器将不会继续,但是当您导航到应用程序内部的另一个页面时,计时器将继续。你可以这样防止它:

        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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-13
      • 1970-01-01
      相关资源
      最近更新 更多