当前位置:  开发笔记 > 编程语言 > 正文

在页面构造函数中异步调用Web服务

如何解决《在页面构造函数中异步调用Web服务》经验,为你挑选了1个好方法。



1> Andrii Krupk..:

相反,您需要使用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 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;
    }

}

推荐阅读
jerry613
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有