在为 Windows Phone 8.1 加载页面后,长 运行 代码的最佳事件处理程序是什么?

What is the best event handler for long running code after a page is loaded for Windows Phone 8.1?

我有很长的 运行ning 代码可以访问我们的服务器以获取更新信息。我希望它在页面加载并可供用户使用后加载。我尝试将此代码放在页面的 OnNavigatedTo() 方法和页面的 Loaded 事件中,但页面 UI 直到异步代码完成后才会加载。我还尝试等待 xaml.cs 代码中的代码,但它也阻止了 UI。我如何 运行 在页面以可视方式加载并为用户交互后编写代码?

您可以将对 await 的调用分离到一个 Task 对象中并单独等待它。

我稍微模拟了一下你的情况

longRunningMethod() :任何长 运行 服务器调用

Button_Click : 这是为了检查 UI 在系统调用服务器期间是否响应。

XAML 文件

<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);
}

这就是你的 UI 的样子 :

我在通话过程中点击了 8 次按钮。