C#-定期刷新方法

C#-定期刷新方法,c#,uwp,refresh,C#,Uwp,Refresh,我想在大约5分钟后定期刷新我的UWP-UI。我有一个方法“Page_Loaded”,其中来自类的所有信息都被发送到UI元素。 所以如果我刷新这个方法,UI也会这样做,对吗 代码如下所示: private async void Page_Loaded(object sender, RoutedEventArgs e) { RootObject myWeather = await Openweathermap.GetWeather();

我想在大约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分钟后刷新此方法,以便它获取新信息并将其发送到UI

反复调用
Page\u Loaded
方法不是推荐的做法,推荐的方法是使用UI线程中的计时器
dispatchermer

我们可以将加载的
页面中的代码提取为函数

private dispatchermer\u定时器;
公共主页()
{
this.InitializeComponent();
_计时器=新调度程序();
_timer.Interval=TimeSpan.frommins(5);
_timer.Tick+=定时器_Tick;
}
专用异步任务GetData()
{
RootObject myWeather=wait Openweathermap.GetWeather();
字符串图标=字符串。格式(“http://openweathermap.org/img/wn/{0}@2x.png”,myWeather.weather[0].icon);
ResultImage.Source=新的位图图像(新的Uri(icon,UriKind.Absolute));
testextblock.Text=((int)myWeather.main.temp).ToString()+“°”;
DescriptionTextBlock.Text=myWeather.weather[0]。说明;
LocationTextBlock.Text=myWeather.name;
var articlesList=NewsAPI.GetNews().Result.articles;
lvNews.ItemsSource=articlesList;
WelcomeText.Text=MainPage.WelcomeText();
}
专用异步无效计时器(对象发送器,对象e)
{
等待GetData();
}
已加载专用异步无效页(对象发送方,RoutedEventArgs e)
{
等待GetData();
_timer.Start();
}
受保护的覆盖无效OnNavigatedFrom(NavigationEventArgs e)
{
_timer.Stop();
基于(e)的导航;
}

使用
dispatchermer.Tick
,我们可以定期执行任务,当我们离开页面时,我们可以停止计时器。

您是否询问使用什么机制来进行5分钟刷新?我认为在UWP中,它被称为
调度程序
。不过,我不会反复调用
Page\u Loaded
事件处理程序,因为您希望将其用于只在加载页面时发生一次的事情,比如设置初始数据并启动计时器。您应该将此代码(最后一行除外)移动到它自己的方法中,然后调用新方法。哦,当我说“调用方法”时,我的意思和你说“刷新方法”时的意思是一样的。