进行 api 调用时 Xamarin 应用程序死锁

问题描述

尝试进行 API 调用(asp.net 核心 Web API)时,我的 Xamarin 应用程序死锁。移动应用程序正在使用 Android 模拟器。我按照 Microsoft 自己的教程创建了 API 和客户端应用程序。使用 Postman 或直接在我的开发机器的浏览器中进行调用时,请求运行正常。

常量类:

public static class Constants
{
        public static string BaseAddress =
        DeviceInfo.Platform == DevicePlatform.Android
          ? "https://10.0.2.2:44348"
          :"https://localhost:44348";

        public static string AppointmentsUrl = $"{BaseAddress}/api/appointments/";
}

处理程序:

public class AppointmentHandler
{
    HttpClient client;
    JsonSerializerOptions serializerOptions;

    private List<Appointment> Appointments { get; set; }

    public AppointmentHandler()
    {
        client = new HttpClient();
        serializerOptions = new JsonSerializerOptions
        {
            PropertyNamingPolicy = JsonNamingPolicy.CamelCase,WriteIndented = true
        };
    }


    public async Task<List<Appointment>> GetAppointments()
    {
        Appointments = new List<Appointment>();
        try
        {
            Uri uri = new Uri(string.Format(Constants.AppointmentsUrl,string.Empty));

            // the program deadlocks here
            HttpResponseMessage response = await this.client.GetAsync(uri);
            
            if (response.IsSuccessstatusCode)
            {
                var content = await response.Content.ReadAsstringAsync();
                return JsonSerializer.Deserialize<List<Appointment>>(content,serializerOptions);
            }

        }
        catch (Exception e)
        {
            var m = e.Message;
        }
        return null;
    }
}

解决方法

你有没有试过使用

.ConfigureAwait(false)

这是异步代码和用户界面的常见问题。更多信息:

https://forums.xamarin.com/discussion/174173/should-i-use-configureawait-bool-or-not