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

Agi*_*obo 3 c# asynchronous xamarin.android async-await xamarin

我正在开发一个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();
    }
Run Code Online (Sandbox Code Playgroud)

这是服务代码

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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

我想念什么吗?谢谢.

Sam*_*nen 9

你不是在等待PostAsync,你只是在接受Result.这使得呼叫同步.

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

        var response = await httpClient.PostAsync(url, new FormUrlEncodedContent(body));
Run Code Online (Sandbox Code Playgroud)