-2

I have an async method like so:

public async Task<LoginClass> LoginAsync(string email, string password)
        {
            var client = new HttpClient();

            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("email", email),
                new KeyValuePair<string, string>("password", password)
            });

            var response = await client.PostAsync(string.Format("/api/v1/login"), content);

            var responseString = await response.Content.ReadAsStringAsync();

            LoginClass items = JsonConvert.DeserializeObject<LoginClass>(responseString);

            return items;

        }

But when I call it in another method like so, its like my app freezes:

WebServiceClass webService = new WebServiceClass();

        public LoginPage()
        {
            InitializeComponent();

            
        }

        protected async void OnLogin(System.Object sender, System.EventArgs e)
        {
            Task<LoginClass> response = webService.LoginAsync(Email.Text, Password.Text);

            if(response.Result.error != null)
            {
                await DisplayAlert("Error", response.Result.error, "OK");
            }

        }

I put a break point on this line:

Task<LoginClass> response = webService.LoginAsync(Email.Text, Password.Text);

The break points, but after that nothing, it does not goto the next line. Its like its waiting for something.

What am I doing wrong and how do I properly call an async method?

user979331
  • 11,039
  • 73
  • 223
  • 418

1 Answers1

0

You have the classic deadlock problem

So,

Never ever ever ever EVER E̓̀̑ͨ̑͐̐͐̽̐̌ͥṼ͑ͭͬ̋̏̈̓Eͮ͑́ͤ̆̅͆̌͋͊͌̽ͯͪ͒ͥ̀R̃̑̎ͩͪ̓Rͥ̐ͯ̾̇Ȑͥ̃̈̐ͣ̈̐ͨ͑̆͋̍R͆ͬ͗ͥ̈́̈́̄ͯ͑̽̓͆ͥ̉ͨR͌͂ͭ̑̎̍͐͂͗ͪ̔͛ͤ call Result, Wait or otherwise block on an async method (unless you completely understand what you are doing), In fact, just don't do it, there is always a better approach. await them instead.

Your code should look like this

var response = await webService.LoginAsync(Email.Text, Password.Text);

if(response.error != null)

Further reading

Stephen Cleary - Don't Block on Async Code

TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • I know you think you're being cute, but please don't put images in posts that don't add anything constructive. Not all of us have unlimited data caps, nor high speed connections, and you're just wasting our bandwidth with pointless stuff like that. It's unprofessional (as is, frankly, the typographical scribble you've also insisted on including). (Not that you should ever have even posted an answer to such an obvious duplicate, but...whatever...) – Peter Duniho Sep 30 '20 at 02:54