首页 > 解决方案 > HttpClient GetAsync 冻结

问题描述

授权后,加载联系页面。该方法在视图模型页面中调用。

public partial class Contacts : ContentPage
        {
            ContactsPageViewModels vm;    
            public Contacts()
            {
                vm = new ContactsPageViewModels();
                BindingContext = vm;
                InitializeComponent();
            }
         }

我试图只发送200ok。一切都来到http分析器,但在应用程序本身它挂在第一行

public async Task<ObservableCollection<UserModel>> GetContactsList()
        {
            //freezes in the first line
            var response = await client.GetAsync("http://localhost:52059/api/Home/GetContacts/" + Convert.ToString(App.User.ID));
            string responseBody = await response.Content.ReadAsStringAsync();
            return JsonConvert.DeserializeObject<ObservableCollection<UserModel>>(responseBody);
        }

控制器

        [HttpGet]
        [Route("GetContacts/{id}")]
        public ActionResult GetContacts(int id)
        {
            ObservableCollection<UserModel> users = new ObservableCollection<UserModel>();

            foreach (UserModel user in db.UserModels)
                users.Add(user); 

            users.Remove(db.UserModels.FirstOrDefault(u => u.ID == id));

            Response.Headers.Add("Content-Type", "application/json");

            //return Ok();
            return new JsonResult(users);
        }

在邮递员所有工作

标签: c#asp.netxamarinxamarin.forms

解决方案


这听起来像是同步上下文和应用程序主线程上的问题。

在此处此处阅读更多信息。

尝试:

public async Task<ObservableCollection<UserModel>> GetContactsList()
{
    var response = await client.GetAsync("http://localhost:52059/api/Home/GetContacts/" + Convert.ToString(App.User.ID)).ConfigureAwait(false);
    string responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
    return JsonConvert.DeserializeObject<ObservableCollection<UserModel>>(responseBody);
}

发生的是死锁,因为主线程正在等待异步结束。并且 async 想要回到线程结束 async - 但不能,因为主线程正在等待它。

.ConfigureAwait(false)

会说(不深入研究状态机以及异步/等待如何工作)它将在其他一些线程上结束,即调用(主/同步)线程。


推荐阅读