2015-03-03 51 views
1

我長時間運行代碼,點擊我們的服務器獲取更新信息。我希望它在用戶加載和使用頁面之後加載。我試着把這段代碼放在頁面的OnNavigatedTo()方法和頁面的Loaded事件中,但是直到異步代碼完成後才加載頁面UI。我也嘗試在xaml.cs代碼後面等待代碼,但它也阻止了UI。如何在頁面以可視方式加載併爲用戶交互後運行代碼?爲Windows Phone 8.1加載頁面後,長時間運行代碼的最佳事件處理程序是什麼?

回答

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

+0

問題是我沒有使用長時間運行的「服務器」調用方法。長時間運行的方法在本地硬件上運行。由於該方法是在本地運行的,因此代碼中沒有足夠時間重新加載/繪製的任何地方。因此,如果我在長時間運行(本地)異步方法的開始處放置任意Task.Delay,它將爲UI線程提供足夠的時間來繪製UI元素。感謝您的全面回答。 – WiteCastle 2015-03-21 04:20:26

相關問題