Pergunta

I'm trying to create an application that will fetch data from a web API and display it, then continuously refresh the data every 5 seconds or so, but I don't know the best way to go about doing this.

My first thought was just a simple timer, doing something like what was done in this question, but I'm worried that I may mess it up and have the timer continue running in the background when it shouldn't be (like if the user leaves the page). Am I worried over something that isn't going to actually happen? Is this a good way to go about doing what I'm trying to do, or is there a more efficient/safe way of doing this?

Foi útil?

Solução

When you navigate outside app, timer will not continue, but when you navigate to another page inside app, timer will continue. You can prevent it this way:

    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
    }

Moreover, if you are just checking for data which most time is not changed, consider using push notifications.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top