使用async / await仍会阻止Xamarin.Android上的UI

时间:2016-07-29 13:48:56

标签: c# asynchronous xamarin xamarin.android async-await

我正在开发一个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;
        }
    }

我错过了什么吗?谢谢。

1 个答案:

答案 0 :(得分:9)

您不是在等待PostAsync,而是在等Result。这使得呼叫同步。

将该行更改为等待,它将以异步方式运行。

        var response = await httpClient.PostAsync(url, new FormUrlEncodedContent(body));