xamarin.forms - 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 收到的国家/地区名称。
有人可以帮助我了解我在这里缺少什么吗?
谢谢 !
问候,
解决方案
推荐阅读
- sql - 为什么一个视图有一个惊人的时间曲线和极限?
- java - 为什么 Java 类可以在方法中声明和初始化该类的对象?
- wordpress - CSV 文件未在 Wordpress 上上传
- python - 在格式化 JSON 响应时,迭代 SQL 关系的最有效方法是什么?
- php - if 条件中出现意外的标识符语法错误
- java - 为什么连接 BLE 设备时 bluetoothAdapter 回调会抛出错误?
- java - Spring Boot AnnotationConfigEmbeddedWebApplicationContext 无法填充动态类中的自动装配声明字段
- sql-server - 如何检查 SQL Server 中的日期时间格式?
- android - Android TextView 文本不出现
- sql - oracle sql:插入长文本但接收 SP2-0778:脚本文件名和参数太长