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

本文关键字:调用 web 服务 异步 构造函数 | 更新日期: 2023-09-27 18:25:25

我需要在windows 10 UWP应用程序的XAML页面上加载数据。为此,我编写了在异步任务函数中调用web服务的代码,并在页面构造函数中调用它。你们能告诉我最好的方法吗?以下是我的代码。

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

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

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