使用async/await仍然会阻塞Xamarin上的UI.安卓

本文关键字:Xamarin 上的 UI 安卓 async await 使用 | 更新日期: 2023-09-27 17:59:16

我正在研制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;
        }
    }

我错过什么了吗?非常感谢。

使用async/await仍然会阻塞Xamarin上的UI.安卓

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

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

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