模拟器挂起,任务状态为 WaitingForActivation

Emulator hangs with Task status WaitingForActivation

我正在尝试从 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);
        }
    }

但是,当我尝试用一​​个单独的 class 方法编写此代码并按如下方式从单击事件调用它时,它在单击事件时挂起并且数据状态为 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
    }

谁能告诉我哪里做错了?

提前感谢您的帮助。

你是 causing a deadlock by calling Result,我在我的博客上对此进行了详细解释。

最好的解决方案是 use async "all the way",正如我在关于 async 最佳实践的 MSDN 文章中所述。

在这种特殊情况下,将 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 重命名为 GetApiAsync,以遵循 common naming patterns.