簡體   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