I am new to UWP and trying to call data from the internet which needs around 5 seconds to be loaded. The data will then be displayed in a grid. The problem I am facing is that the whole application is blocked until the data arrives. (the logic exists in Home.xaml which is a page that will be rendered inside a frame in the MainPage.xaml)
I added so far:
private void WeatherGrid_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
var weatherService = new WeatherService();
var weather = weatherService.GetCurrentWeather(); // this takes around 5 seconds to be fetched
this.TemperatureTextBlock.Text = weather.Main.Temp.ToString();
}
and my XAML Code:
<Grid Loaded="WeatherGrid_Loaded">
<TextBlock x:Name="TemperatureTextBlock"></TextBlock>
</Grid>
What I am trying to achieve is for the main page and the home to be loaded and functional and the weather data to be loaded in a thread and when they are fetched, the value will be displayed inside the textblock. If there is an inturreption (change of page or refresh) the process should stop and/or restart again. I don't know to be honest how to start with it as I am used to web development. Any suggestions?
Unless GetCurrentWeather
is async
or there is an async
overload of it available, you should call it on a background thread using the Task.Run
API:
private async void WeatherGrid_Loaded(object sender, Windows.UI.Xaml.RoutedEventArgs e)
{
var weatherService = new WeatherService();
var weather = await Task.Run(() => weatherService.GetCurrentWeather());
this.TemperatureTextBlock.Text = weather.Main.Temp.ToString();
}