Xamarin Forms 如何调用异步方法 [英] Xamarin Forms How to call an async method

查看:62
本文介绍了Xamarin Forms 如何调用异步方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的异步方法:

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?

推荐答案

您遇到了经典的死锁问题

You have the classic deadlock problem

所以,

永远不要 EVER E̓̑ͨ̑͐̐͐̽̐̌ͥṼ͑ͭͬ̋̏̈̓Eͮ͑ͤ̆̅͆̌͋͊͌̽ͯͪ͒ͥȒͩͪ̓Rͥ̐ͯ̾̇Ȑͥ̈̐ͣ̈̐ͨ͑̆͋̍R͆ͬ͗ͥ̈̈̄ͯ͑̽̓͆ͥ̉ͨR͌ͭ̑̍͐͗ͪ̔͛ͤasync 方法上调用 ResultWait 或以其他方式阻塞(除非你完全理解你在做什么),事实上,不要这样做,有总是更好的方法.await 代替.

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.

你的代码应该是这样的

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

if(response.error != null)


进一步阅读

Stephen Cleary - 不要阻止异步代码

这篇关于Xamarin Forms 如何调用异步方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆