【问题标题】:Calling web service asynchronously in page constructor在页面构造函数中异步调用 Web 服务
【发布时间】:2016-03-08 01:53:27
【问题描述】:

我需要在 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;
    }
}

【问题讨论】:

    标签: c# uwp windows-10-universal


    【解决方案1】:

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

    【讨论】:

    • 如果我想在加载数据时保留一个微调器。我需要在哪里保留它?
    • 据我了解,您可以添加 ProgressRing 或 ProgressBar 并确定 Active 状态和 Visiblity
    猜你喜欢
    • 2020-07-28
    • 2018-09-16
    • 1970-01-01
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多