【问题标题】:What is the best event handler for long running code after a page is loaded for Windows Phone 8.1?为 Windows Phone 8.1 加载页面后,长时间运行代码的最佳事件处理程序是什么?
【发布时间】:2015-03-03 03:43:40
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

    您可以将 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);
    }
    

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

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

    【讨论】:

    • 这个问题是我没有使用长时间运行的“服务器”调用方法。长时间运行方法在本地硬件上运行。由于该方法在本地运行,因此代码中没有任何地方可以为 UI 提供足够的时间来重新加载/绘制。因此,如果我在长时间运行(本地)异步方法的开头放置一个任意 Task.Delay,它会给 UI 线程足够的时间来绘制 UI 元素。感谢您的详尽回答。
    猜你喜欢
    • 1970-01-01
    • 2015-03-31
    • 1970-01-01
    • 2010-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多