我正在尝试从API中获取数据。
当我用如下所示的方法编写所有代码时,它可以正常工作。
private async void btvalidate_Click(object sender, RoutedEventArgs e)
{
try
{
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("mybaseaddress");
HttpResponseMessage response = await client.GetAsync("mylocaluri");
if (response.IsSuccessStatusCode)// check whether response status is true
{
var data = response.Content.ReadAsStringAsync();//read the data in the response
var msg = JsonConvert.DeserializeObject<myclassname>(data.Result.ToString());//convert the string response in json format
validate.DataContext = msg;// assign the data received to stackpanel
}
}
catch (Exception ex)
{
MessageBox.Show("Somethimng went wrong" + ex);
}
}
但是当我尝试在单独的类的方法中编写此代码并从click事件中调用它时,如下所示,它会在事件点击时挂起并且具有数据状态为WaitingforActivation ...
public class API
{
public async Task<string> getAPI(string uri)
{
string data1 = null;
var data=data1;
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri("mybaseaddress");
HttpResponseMessage response = await client.GetAsync(uri);
if (response.IsSuccessStatusCode)// check whether response status is true
{
data = response.Content.ReadAsStringAsync().Result;//read the data in the response
}
}
return data;
}
}
private void btcount_Click(object sender, RoutedEventArgs e)
{
var data = api.getAPI("mylocaluri");
var msg = JsonConvert.DeserializeObject<myclassname>(data.Result.ToString());//convert the string response in json format
validate.DataContext = msg;// assign the data received to stackpanel
}
有人能告诉我我做错了吗?
提前感谢您的帮助。
答案 0 :(得分:3)
你causing a deadlock by calling Result
,我在博客上完整解释。
最好的解决方案是use async
"all the way",正如我在MSDN上关于%
最佳做法的文章中所述。
在这种特殊情况下,请将async
替换为Result
:
await
在旁注中,请考虑将private async void btcount_Click(object sender, RoutedEventArgs e)
{
var data = await api.getAPI("mylocaluri");
var msg = JsonConvert.DeserializeObject<myclassname>(data.ToString());//convert the string response in json format
validate.DataContext = msg;// assign the data received to stackpanel
}
重命名为getAPI
,然后关注common naming patterns。