duckmike
duckmike

Reputation: 1036

Awaiting httpclient

Here is the code -

VERSION 3: Remove r.result and it still doesn't work.

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;
}

The await call to post the username and password and get a token never returns.

Am I doing something incorrect?

Upvotes: 0

Views: 66

Answers (1)

SLaks
SLaks

Reputation: 887195

You're accessing r.Result, which blocks on the Task, on the UI thread.
This creates a deadlock, since the inner await tries to resume on the UI thread.

You need to await it instead.

Upvotes: 1

Related Questions