【问题标题】:Using async/await still blocks UI on Xamarin.Android使用 async/await 仍会阻止 Xamarin.Android 上的 UI
【发布时间】:2016-07-29 13:48:56
【问题描述】:

我正在开发一个 Xamarin.Android 项目,该应用需要在更新 UI 之前使用 Web 服务。我应用了 async/await,但它仍然阻塞了 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;
        }
    }

我错过了什么吗?谢谢。

【问题讨论】:

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


【解决方案1】:

你不是在等待PostAsync,你只是在等待Result。这使得调用同步。

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

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

【讨论】:

  • 谢谢萨米。它解决了问题。
猜你喜欢
  • 1970-01-01
  • 2016-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-11
  • 2016-06-13
  • 2018-05-16
  • 2014-01-04
相关资源
最近更新 更多