1

I'm new to Xamarin and I'm trying to create a cross-platform app where users can login using a JSON API call. A token is then returned on a successful login attempt which I can use in other API's to display user data. It works when I use the same code in a console application, but when I run it in Xamarin the code after await client.GetAsync(url) is never reached and after a while the application breaks and I get an unknown error. Am I experiencing a deadlock?

  private async void loginButton_Click(object sender, EventArgs e)
    {
        var login = await loginAPI(LoginPage.nameEntry.Text, LoginPage.passEntry.Text);
        if (login.state == "success")
        {
            ...
        }
        else
        {
            ...
        }
    }
    public static async Task<LoginData> loginAPI(String username, String password)
    {
        try
        {
            using (var client = new HttpClient())
            {
                var loginUrl = new Uri("https://my-api/login?username=" + username + "&password=" + password);

                var result = await client.GetAsync(loginUrl);

                return JsonConvert.DeserializeObject<LoginData>(await result.Content.ReadAsStringAsync());

            }
        }
        catch (Exception e)
        {
            return null;
        }
    }
    public class LoginData
    {
        [JsonProperty("state")]
        public String state { get; set; }
        [JsonProperty("token")]
        public String token { get; set; }

    }
Emile
  • 11
  • 4
  • I don't see anything that should cause a deadlock, but it could be a thread affinity issue. Firstly you should not need (or want) to use ConfigureAwait(false) on the call to `loginAPI(LoginPage.nameEntry.Text, LoginPage.passEntry.Text).ConfigureAwait(false);` as you do likely want to return to the UI thread once that call is completed. In fact in this scenario I don't think you really need to call that at all. See what happens if you remove all of the `ConfigureAwait(false);` calls. If it works then, then it is likely a thread affinity issue. – jgoldberger - MSFT Mar 09 '17 at 00:55
  • I only added `.ConfigureAwait(false)` due to the code not working in the first place and because it seemed to solve the problem for others. Thanks for the response though, I'll remove it. – Emile Mar 10 '17 at 08:22
  • Did you examine the exception? Seems like `GetAsync` throws an error – VMAtm Mar 10 '17 at 17:08

0 Answers0