微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决进行 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。