异步Task <>函数的结果只是阻止程序运行

时间:2019-11-30 15:49:38

标签: c# android .net firebase xamarin

所以,我试图从Firebase的User表中获取数据,然后返回并尝试将结果设置为Label,然后屏幕变成全白(如果有问题,我正在将xamarin用于android),但没有任何反应。也许我做错了什么,或者我错过了某些事情,我对任务的工作方式也有些模糊。我任何人都有任何想法,请随意给我任何指示或任何其他选择。这是我使用的代码 谢谢

UserDetailsRetrive.cs

public async Task<UserDetails> getUserInfoDetails()
        {
            FirebaseClient client = new FirebaseClient("https://xyz.firebaseio.com/");
            return (UserDetails)(await client.Child("user").OnceAsync<UserDetails>()).Select(item => new UserDetails
            {
                first_name = item.Object.first_name,
                last_name = item.Object.last_name,
                username = item.Object.username,
                birthdate = item.Object.birthdate,
                newsletter = item.Object.newsletter,
                term_condition = item.Object.term_condition
            });

Profile.cs

 public void setUserInfo()
        {

            UserDetailsRetreive usr = new UserDetailsRetreive();
            UserDetails userDetails = usr.getUserInfoDetails().Result;
            username.Text = userDetails.username.ToString();


        }

UserDetails.cs

class UserDetails
    {
        public string first_name { get; set; }
        public string last_name { get; set; }
        public string username { get; set; }
        public string birthdate { get; set; }
        public bool newsletter { get; set; }
        public bool term_condition { get; set; }


    }

1 个答案:

答案 0 :(得分:0)

Task.Result将阻塞,直到Task完成为止,这就是为什么您遇到UI冻结的原因。为了解决这个问题,您需要异步调用usr.getUserInfoDetails

public async Task setUserInfo()
{
    UserDetailsRetreive usr = new UserDetailsRetreive();
    UserDetails userDetails = await usr.getUserInfoDetails();
    username.Text = userDetails.username.ToString();
}