c# - 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);
}
在邮递员所有工作
解决方案
这听起来像是同步上下文和应用程序主线程上的问题。
尝试:
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)
会说(不深入研究状态机以及异步/等待如何工作)它将在其他一些线程上结束,即调用(主/同步)线程。
推荐阅读
- c# - ComboBox.SelectedValue 返回 ToString() 而不是 Name 属性
- python - 如何在python中绘制具有不同X索引的多条线
- ios - Swift:如何从导航控制器过渡到标签栏控制器
- javascript - 如何使用 axios 和文件 URL 读取文件内容?
- python - 在python中使用步长计算滑动窗口
- jmeter - 在 JSR223 断言中定义一个值并从不同线程中的用户定义变量访问它
- r - 为什么会报错说找不到对象?
- reactjs - 如何从文件外部导入?
- python - Pyspark:K 表示模型拟合时的聚类误差
- css - CSS中的Gotham Medium / black字体定义