Call a web service asynchronously in the page constructor

I need to load data on a XAML page in a Windows 10 UWP application. To do this, I wrote code to invoke the web service in the async task function, and I call this in the page constructor. Could you tell us the best way to do this? The 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;
    }
}
+4
source share
1 answer

Instead, you need to use OnNavigatedTo

because, GetDownloads().Wait()bad practice. You block the user interface 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;
    }

}
+5
source

Source: https://habr.com/ru/post/1618429/


All Articles