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

时间:2015-03-03 03:43:40

标签: c# xaml windows-runtime windows-phone-8.1 winrt-xaml

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

1 个答案:

答案 0 :(得分:0)

您可以将等待的呼叫分成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);
}

这就是您的用户界面的样子

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

enter image description here