C# 在为Windows Phone 8.1加载页面后,对于长时间运行的代码,最好的事件处理程序是什么?

C# 在为Windows Phone 8.1加载页面后,对于长时间运行的代码,最好的事件处理程序是什么?,c#,xaml,windows-runtime,windows-phone-8.1,winrt-xaml,C#,Xaml,Windows Runtime,Windows Phone 8.1,Winrt Xaml,我有一个长时间运行的代码,可以点击我们的服务器获取更新信息。我希望它加载后,页面加载和可用的用户。我尝试将此代码放入页面的OnNavigatedTo方法和页面的Loaded事件中,但页面UI直到异步代码完成后才加载。我还尝试等待xaml.cs代码中的代码,但它也会阻塞UI。页面可视加载并与用户交互后,如何运行代码?您可以将对wait的调用分离到任务对象中,然后分别对其进行等待 我试着稍微模拟一下你的处境 longRunningMethod:任何长时间运行的服务器调用 按钮单击:这是为了检查UI在

我有一个长时间运行的代码,可以点击我们的服务器获取更新信息。我希望它加载后,页面加载和可用的用户。我尝试将此代码放入页面的OnNavigatedTo方法和页面的Loaded事件中,但页面UI直到异步代码完成后才加载。我还尝试等待xaml.cs代码中的代码,但它也会阻塞UI。页面可视加载并与用户交互后,如何运行代码?

您可以将对wait的调用分离到任务对象中,然后分别对其进行等待

我试着稍微模拟一下你的处境

longRunningMethod:任何长时间运行的服务器调用

按钮单击:这是为了检查UI在系统进行服务器调用期间是否有响应

XAML文件

这是您的UI的外观:

我在通话中按了8次按钮


问题是我没有使用长时间运行的服务器调用方法。长时间运行的方法在本地硬件上运行。由于该方法在本地运行,因此代码中没有任何地方给UI足够的时间重新加载/绘制。因此,如果我在长时间运行的本地异步方法开始时放置任意Task.Delay,它会给UI线程足够的时间来绘制UI元素。谢谢你详尽的回答。
<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>
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);
}