Calling web service asynchronously in page constru

2019-06-26 04:10发布

问题:

I need to load data on a XAML page in a windows 10 UWP application. For that I wrote code to call the web service in async task function, and I call this in page constructor. 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;
    }
}

回答1:

Instead that you need use OnNavigatedTo

because, GetDownloads().Wait() bad practice. You block UI Thread until the end of execution

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;
    }

}