首页 > 解决方案 > Xamarin App 在等待 GetAsync 方法后什么也不做

问题描述

我在 Xamarin Forms 中创建了一个类,该类向 Web API 请求有关国家/地区的详细信息。现在,我只在一个国家/地区进行测试。

但是,一旦出现“HttpResponseMessage response = await client.GetAsync(uri);”行 执行后,该应用程序不执行任何其他操作。

为了验证应用程序是否在此行之后执行其他指令,我添加了额外的行以将序列写入设备日志。

上一条指令之前的所有行都写入日志,而这条指令之后的行都没有。

另一方面,设备的屏幕保持空白,没有插入代码创建的标签。

这是类的代码和使用 API 的方法。

...

using Android.Util;
using System.Net.Http;
using System.Threading.Tasks;

class Country
{
    public int iIdCountry { get; set; }
    public string sCountryName { get; set; }
    public string sCountryIsoCode { get; set; }
    public string sCountryPhoneCode { get; set; }
    public bool bCountryContainsPrefix { get; set; }
    public bool bCountryActive { get; set; }

    private static readonly HttpClient client = new HttpClient();

    public static async Task<Country> GetCountryAsync(int id)
    {
        string baseUri = new BaseUri().baseUri;
        string sufixUri = "/CountriesApi/GetItem/" + id;
        var uri = baseUri + sufixUri;
        string tag = "myapp";
        Country country = null;

        HttpResponseMessage response = await client.GetAsync(uri);
        Log.Info(tag, "Response received");

        if (response.IsSuccessStatusCode)
        {
            country = await response.Content.ReadAsAsync<Country>();
            Log.Info(tag, "Country received");
        }

        Log.Info(tag, "Country returned");
        return country;
    }
}

...

这是调用上一个类的组件:

...

using Android.Util;
using System;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace EnubexMobile.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]

    public partial class Start : ContentPage
    {
        public Start()
        {
            var stackLayout = new StackLayout();
            string tag = "myapp";

            InitializeComponent();
            Log.Info(tag, "Started");

            var country = Country.GetCountryAsync(1).GetAwaiter().GetResult();
            Log.Info(tag, country.sCountryName);

            var label = new Label() { Text = country.sCountryName };
            Log.Info(tag, "Label created");

            stackLayout.Children.Add(label);
            Log.Info(tag, "Label added");
        }

        private void InitializeComponent()
        {
            throw new NotImplementedException();
        }
    }
}

...

这个想法是在 StackLayout 中插入一个标签,其中包含从 API 收到的国家/地区名称。

有人可以帮助我了解我在这里缺少什么吗?

谢谢 !

问候,

标签: xamarin.formsasync-awaitwebapigetasync

解决方案


推荐阅读