2016-07-29 13 views
1

Ich bin auf einem Xamarin.Android Projekt arbeiten und die App muss Web-Service verbrauchen, bevor die Benutzeroberfläche zu aktualisieren. Ich habe async/await angewendet, blockiert aber immer noch die Benutzeroberfläche.Mit async/warten noch auf UI-Blöcke auf Xamarin.Android

Hier ist die UI-Code

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(); 
    } 

Hier wird der Servicecode

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; 
     } 
    } 

Habe ich etwas verpasst? Vielen Dank.

+0

Es ist normalerweise eine schlechte Idee, den asynchronen Code durch Aufrufen von Task.Wait oder Task.Result zu blockieren. https://msdn.microsoft.com/en-us/magazine/jj991977.aspx –

+0

Dank Jon. Ich habe viel aus dem Artikel gelernt. –

Antwort

9

Sie sind nicht PostAsync erwartet, Sie nehmen nur die Result. Dies macht den Anruf synchron.

Ändern Sie diese Zeile, um zu warten, und sie wird asynchron ausgeführt.

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

Danke Sami. Es hat das Problem behoben. –