从Android应用程序调用Azure Web API只是等待响应时挂起
我已经向Azure发布了一个非常基本的asp.net web api代码,该代码随模板一起提供。当我尝试默认的GET操作时,我得到JSON响应["value1","value2"]
从Android应用程序调用Azure Web API只是等待响应时挂起
当我尝试从我的xamarin-android项目进行相同的调用时,执行只是在等待响应时永远挂起(请参阅下面的代码)。
我使用visual studio 2015.我连接手机进行调试。
button.Click += onButtonClick;
}
private void onButtonClick(object sender, EventArgs e)
{
GetValuesSync().Wait();
}
private async Task GetValuesSync()
{
string ResponseJsonString = null;
string url =
"http://myWebapp.azurewebsites.net/api/values";
using (var httpClient = new HttpClient())
{
try
{
Task<HttpResponseMessage> getResponse = httpClient.GetAsync(url);
HttpResponseMessage response = await getResponse; //Execution hangs here forever ...
ResponseJsonString = await response.Content.ReadAsStringAsync();
values = JsonConvert.DeserializeObject<string[]>(ResponseJsonString);
}
catch (Exception ex)
{
throw;
}
}
}
感谢您的帮助
除上述答案外,作为最佳实践,请始终指定应在哪个线程上调用await之后的延续。在你的情况下,显式调用ConfigureAwait(false)也应该解决死锁问题。
的确,我忘了补充一点。谢谢! –
似乎这个问题更多地与我缺乏异步编程知识相关,而不是xamarin android的工作方式。我有很多事情要做。无法分辨将等待放在前面和在对象本身上调用等待之间的区别。 – Richard77
它总是最好离开异步工作流异步。强制使其同步将基本上阻止你的UI线程,该应用程序将失去其响应。
如果您尝试这样的事情是什么:
private async void onButtonClick(object sender, EventArgs e)
{
await GetValuesAsync();
}
private async Task GetValuesAsync()
{
string ResponseJsonString = null;
string url =
"http://myWebapp.azurewebsites.net/api/values";
using (var httpClient = new HttpClient())
{
try
{
Task<HttpResponseMessage> getResponse = httpClient.GetAsync(url);
HttpResponseMessage response = await getResponse; //Execution hangs here forever ...
ResponseJsonString = await response.Content.ReadAsStringAsync();
values = JsonConvert.DeserializeObject<string[]>(ResponseJsonString);
}
catch (Exception ex)
{
throw;
}
}
}
我希望values
没有连接到用户界面,或者您可能需要访问UI线程更新它。
这里有死锁'GetValuesSync()。Wait();'。 –
@ Richard77:我推荐阅读我的[关于异步最佳实践的MSDN文章](https://msdn.microsoft.com/en-us/magazine/jj991977.aspx)和我的博客文章[不要阻止异步代码] (http://blog.stephencleary.com/2012/07/dont-block-on-async-code.html)。 –