繁体   English   中英

HttpClient GetAsync 冻结

[英]HttpClient GetAsync freezes

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

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);
        }

Controller

        [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);
        }

在 postman 全部工作

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

在这里阅读更多:

https://devblogs.microsoft.com/dotnet/configureawait-faq/

或在这里:

https://medium.com/bynder-tech/c-why-you-should-use-configureawait-false-in-your-library-code-d7837dce3d7f

并尝试:

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)).ConfigureAwait(false);
    string responseBody = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
    return JsonConvert.DeserializeObject<ObservableCollection<UserModel>>(responseBody);
}

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

.ConfigureAwait(false)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM