2015-12-03 63 views
4

我需要在Windows 10 UWP應用程序的XAML頁面上加載數據。爲此,我編寫了代碼來調用異步任務函數中的Web服務,並在頁面構造函數中調用此函數。你能告訴我最好的辦法嗎?以下是我的代碼。在頁面構造函數中異步調用Web服務

public sealed partial class MyDownloads : Page 
{ 
    string result; 
    public MyDownloads() 
    { 
     this.InitializeComponent(); 

     GetDownloads().Wait(); 
     string jsonstring = result; 

     //code for binding follows 
    } 

    private async Task GetDownloads() 
    { 
     JsonObject jsonObject = new JsonObject 
     { 
      {"StudentID", JsonValue.CreateStringValue(user.Student_Id.ToString()) }, 
     }; 

     string ServiceURI = "http://m.xxx.com/xxxx.svc/GetDownloadedNotes"; 
     HttpClient httpClient = new HttpClient(); 
     HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, ServiceURI); 

     request.Content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json"); 

     HttpResponseMessage response = await httpClient.SendAsync(request); 
     string returnString = await response.Content.ReadAsStringAsync(); 
     result = returnString; 
    } 
} 

回答

5

相反,你需要使用的OnNavigatedTo

因爲,GetDownloads().Wait()不好的做法。你屏蔽UI線程直到執行結束

public sealed partial class MainPage : Page 
{ 
    public MainPage() 
    { 
     this.InitializeComponent(); 
    } 

    protected override async void OnNavigatedTo(NavigationEventArgs e) 
    { 
     base.OnNavigatedTo(e); 

     var result = await GetDownloadsAsync(); 
     string jsonstring = result; 
    } 

    private async Task<string> GetDownloadsAsync() 
    { 
     JsonObject jsonObject = new JsonObject 
     { 
      {"StudentID", JsonValue.CreateStringValue(user.Student_Id.ToString()) }, 
     }; 

     string ServiceURI = "http://m.xxx.com/xxxx.svc/GetDownloadedNotes"; 
     HttpClient httpClient = new HttpClient(); 
     HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, ServiceURI); 

     request.Content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json"); 

     HttpResponseMessage response = await httpClient.SendAsync(request); 
     string returnString = await response.Content.ReadAsStringAsync(); 
     return returnString; 
    } 

} 
+0

如果我想在加載數據時保持一個微調,我需要保留它嗎? – arun

+1

據我所知,您可以添加ProgressRing或ProgressBar並確定活動狀態和Visiblity –