Calling web service asynchronously in page constructor

喜你入骨 提交于 2019-12-12 12:09:28

问题


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

}


来源:https://stackoverflow.com/questions/34066196/calling-web-service-asynchronously-in-page-constructor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!