Search code examples
c#uwprefresh

C# - Refresh method periodically


I want to refresh my UWP-UI periodically after like 5 minutes. I have a Method "Page_Loaded" where all information from the classes is sent to the UI-Elements. So if i refresh this method, the UI would do too, right?

The Code is like this:

private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            RootObject myWeather = await Openweathermap.GetWeather();
            string icon = String.Format("http://openweathermap.org/img/wn/{0}@2x.png", myWeather.weather[0].icon);
            ResultImage.Source = new BitmapImage(new Uri(icon, UriKind.Absolute));

            TempTextBlock.Text = ((int)myWeather.main.temp).ToString() + "°";
            DescriptionTextBlock.Text = myWeather.weather[0].description;
            LocationTextBlock.Text = myWeather.name;

            var articlesList = NewsAPI.GetNews().Result.articles;
            lvNews.ItemsSource = articlesList;

            Welcometxt.Text = MainPage.WelcomeText();
        }

So, how do I refresh this method after 5 Minutes, so that it gets the new information and sends it to the UI?


Solution

  • So, how do I refresh this method after 5 Minutes, so that it gets the new information and sends it to the UI?

    Repeatedly calling the Page_Loaded method is not a recommended practice, the recommended approach is to use DispatcherTimer, a timer within the UI thread.

    We can extract the code inside Page_Loaded as a function.

    private DispatcherTimer _timer;
    public MainPage()
    {
        this.InitializeComponent();
        _timer = new DispatcherTimer();
        _timer.Interval = TimeSpan.FromMinutes(5);
        _timer.Tick += Timer_Tick;
    }
    
    private async Task GetData()
    {
        RootObject myWeather = await Openweathermap.GetWeather();
        string icon = String.Format("http://openweathermap.org/img/wn/{0}@2x.png", myWeather.weather[0].icon);
        ResultImage.Source = new BitmapImage(new Uri(icon, UriKind.Absolute));
    
        TempTextBlock.Text = ((int)myWeather.main.temp).ToString() + "°";
        DescriptionTextBlock.Text = myWeather.weather[0].description;
        LocationTextBlock.Text = myWeather.name;
    
        var articlesList = NewsAPI.GetNews().Result.articles;
        lvNews.ItemsSource = articlesList;
    
        Welcometxt.Text = MainPage.WelcomeText();
    }
    
    private async void Timer_Tick(object sender, object e)
    {
        await GetData();
    }
    
    private async void Page_Loaded(object sender, RoutedEventArgs e)
    {
        await GetData();
        _timer.Start();
    }
    
    protected override void OnNavigatedFrom(NavigationEventArgs e)
    {
        _timer.Stop();
        base.OnNavigatedFrom(e);
    }
    

    With DispatcherTimer.Tick, we can execute tasks regularly, and when we leave the page, we can stop the timer.