2015-12-03 86 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 –