[英]Calling web service asynchronously in page constructor
I need to load data on a XAML page in a windows 10 UWP application. 我需要在Windows 10 UWP应用程序中的XAML页面上加载数据。 For that I wrote code to call the web service in async task function, and I call this in page constructor. 为此我编写了代码来在异步任务函数中调用Web服务,我在页面构造函数中调用它。 Could you please tell best way to do this? 你能告诉我最好的办法吗? Following is my code. 以下是我的代码。
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;
}
}
Instead that you need use OnNavigatedTo 相反,您需要使用OnNavigatedTo
because, GetDownloads().Wait()
bad practice. 因为, GetDownloads().Wait()
不好的做法。 You block UI Thread until the end of execution 您阻止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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.