【问题标题】:C# - Refresh method periodicallyC# - 定期刷新方法
【发布时间】:2020-06-19 10:50:24
【问题描述】:

我想在 5 分钟后定期刷新我的 UWP-UI。我有一个方法“Page_Loaded”,其中来自类的所有信息都发送到 UI 元素。 所以如果我刷新这个方法,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?

【问题讨论】:

  • 您是在问使用什么机制来进行 5 分钟刷新?我认为在 UWP 中它被称为DispatcherTimer。我不会一遍又一遍地调用Page_Loaded 事件处理程序,因为您希望将其用于仅在页面加载时发生一次的事情,例如设置初始数据并启动计时器。您应该将此代码(最后一行除外)移动到它自己的方法中,然后调用新方法。哦,当我说“调用方法”时,我的意思与您说“刷新方法”时的意思相同。

标签: c# uwp refresh


【解决方案1】:

那么,如何在 5 分钟后刷新此方法,以便它获取新信息并将其发送到 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,我们可以定时执行任务,离开页面时可以停止定时器。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-06-13
    • 2013-09-13
    • 1970-01-01
    • 1970-01-01
    • 2019-12-18
    • 2017-04-16
    • 2012-07-02
    相关资源
    最近更新 更多