3

I'm working on a Xamarin.Android project and the app needs to consume web service before updating the UI. I applied async/await but it still blocks the UI.

Here is the UI code

    private async void Login(object sender, EventArgs e)
    {
        var username = _usernamEditText.Text.Trim();
        var password = _passwordEditText.Text.Trim();
        var progressDialog = ProgressDialog.Show(this, "", "Logging in...");
        var result = await _userService.AuthenticateAsync(username, password);

        progressDialog.Dismiss();
    }

Here is the service code

public async Task<AuthenticationResult> AuthenticateAsync(string username, string password)
    {
        using (var httpClient = CreateHttpClient())
        {
            var url = string.Format("{0}/token", Configuration.ServiceBaseUrl);
            var body = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("username", username),
                new KeyValuePair<string, string>("password", password),
                new KeyValuePair<string, string>("grant_type", "password")
            };
            var response = httpClient.PostAsync(url, new FormUrlEncodedContent(body)).Result;
            var content = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
            var obj = new JSONObject(content);
            var result = new AuthenticationResult {Success = response.IsSuccessStatusCode};

            if (response.IsSuccessStatusCode)
            {
                result.AccessToken = obj.GetString("access_token");
                result.UserName = obj.GetString("userName");
            }
            else
            {
                result.Error = obj.GetString("error");

                if (obj.Has("error_description"))
                {
                    result.ErrorDescription = obj.GetString("error_description");
                }
            }

            return result;
        }
    }

Do I miss anything? Thank you.

2
  • It’s usually a bad idea to block on async code by calling Task.Wait or Task.Result. msdn.microsoft.com/en-us/magazine/jj991977.aspx Commented Jul 29, 2016 at 16:55
  • Thanks Jon. I learnt a lot from the article. Commented Aug 1, 2016 at 7:51

1 Answer 1

9

You're not awaiting PostAsync, you're just taking the Result. This makes the call synchronous.

Change that line to await and it will run asynchronously.

        var response = await httpClient.PostAsync(url, new FormUrlEncodedContent(body));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Sami. It fixed the problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.