C# - 定期刷新方法

C# - Refresh method periodically

我想在大约 5 分钟后定期刷新我的 UWP-UI。我有一个方法 "Page_Loaded",其中来自 类 的所有信息都被发送到 UI-Elements。 所以如果我刷新这个方法,UI 也会这样做,对吧?

代码是这样的:

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();
        }

那么,如何在 5 分钟后刷新此方法,以便它获取新信息并将其发送到 UI?

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

不推荐重复调用 Page_Loaded 方法,推荐的方法是使用 DispatcherTimer,UI 线程中的计时器。

我们可以将Page_Loaded里面的代码提取为一个函数。

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);
}

有了DispatcherTimer.Tick,我们可以定时执行任务,当我们离开页面时,我们可以停止计时器。