等待httpclient

时间:2016-05-06 17:10:12

标签: c#

这是代码 -

版本3:删除r.result但它仍然无法正常工作。

protected async void LogIn(LoginInfo _credentials)
{
    HttpResponseMessage r = await DoLogin("demo", "Abc123$");

    if (r.IsSuccessStatusCode)
    {
        AccountAccess aa = new AccountAccess();

            var x = await r.Content.ReadAsStringAsync();

            aa = JsonConvert.DeserializeObject<AccountAccess>(x);
            Application.Current.Properties["access_token"] = aa.access_token;

    }
    else //if (lr == LoginResult.LoginRes.NoAuth)
    {
        Alert("Alert", "Username/password combination is incorrect", "OK");
    }
}

private async Task<HttpResponseMessage> DoLogin(string username, string password)
{
    HttpClient client = new HttpClient();
    client.BaseAddress = new Uri(Constants.LOGINURL);

    var response = await client.PostAsync("Token", new StringContent("grant_type=password&username=" + username + "&password=" + password, Encoding.UTF8));

    return response;
}

等待调用以发布用户名和密码,并且永远不会返回令牌。

我做错了吗?

1 个答案:

答案 0 :(得分:1)

您正在UI线程上访问任务上阻止的r.Result 这会造成死锁,因为内部await会尝试在UI线程上恢复。

您需要await代替。