I have long running code that hits our server for updated information. I want it to load AFTER the page is loaded and usable by the user. I tried putting this code in the OnNavigatedTo() method of the page and the Loaded event of the page but the page UI doesn't load until after the async code is finished. I also tried awaiting the code in the xaml.cs code behind but it blocks the UI as well. How do I run code after the page is visually loaded and interactive for the user?
You can separate the call for await into a Task
object and await for it separately.
I have tried to simulate your situation to a little extent.
longRunningMethod()
: Any long running server call
Button_Click
: This is to check whether the UI is responsive during the time system is making a server call.
XAML File
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="10*" />
</Grid.RowDefinitions>
<Button Grid.Row="0" Content="Click Me" Click="Button_Click" />
<StackPanel x:Name="stackPanel" Grid.Row="1">
</StackPanel>
</Grid>
Code Behind
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
Task task = longRunningMethod();
TextBlock textBlock = new TextBlock();
textBlock.FontSize = 40;
textBlock.Text = "Started"; //UI is loaded at this point of time
stackPanel.Children.Add(textBlock);
await task;
TextBlock textBlock2 = new TextBlock();
textBlock2.FontSize = 40;
textBlock2.Text = "Completed"; // marks the completion of the server call
stackPanel.Children.Add(textBlock2);
}
private async Task longRunningMethod()
{
HttpClient httpClient = new HttpClient();
await Task.Delay(10000);
//dummy connection end point
await httpClient.GetAsync("https://www.google.co.in");
}
//this checks for the responsive of the UI during the time system is making a
//complex server call and ensures that the UI thread is not blocked.
private void Button_Click(object sender, RoutedEventArgs e)
{
TextBlock textBlock = new TextBlock();
textBlock.FontSize = 40;
textBlock.Text = "UI is responding";
stackPanel.Children.Add(textBlock);
}
This is how your UI looks like :
I clicked the button 8 times during the call.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.