Reputation: 322
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.
Upvotes: 3
Views: 3104
Reputation: 31153
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));
Upvotes: 9