[英]Using async/await still blocks UI on Xamarin.Android
我正在开发一个Xamarin.Android项目,应用程序需要在更新UI之前使用Web服务。 我应用了async / await但它仍然阻止了UI。
这是UI代码
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();
}
这是服务代码
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;
}
}
我想念什么吗? 谢谢。
你不是在等待PostAsync
,你只是在拿Result
。 这使得呼叫同步。
将该行更改为等待,它将异步运行。
var response = await httpClient.PostAsync(url, new FormUrlEncodedContent(body));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.