Is it possible to use Task<bool> in if conditions?

丶灬走出姿态 提交于 2019-12-13 12:53:42

问题


In Windows Phone 8 I have method public async Task<bool> authentication(). The return type of the function is bool but when I tried to use its returned value in a if condition error says can not convert Task<bool> to bool.

public async Task<bool> authentication()
{
    var pairs = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string> ("user", _username),
        new KeyValuePair<string, string> ("password", _password)
    };

    var serverData = serverConnection.connect("login.php", pairs);

    RootObject json = JsonConvert.DeserializeObject<RootObject>(await serverData);

    if (json.logined != "false")
    {
        _firsname = json.data.firsname;
        _lastname = json.data.lastname;
        _id = json.data.id;
        _phone = json.data.phone;
        _ProfilePic = json.data.profilePic;
        _thumbnail = json.data.thumbnail;
        _email = json.data.email;
        return true;
    }
    else
        return false;
}

回答1:


The return type of your function is Task<bool>, not bool itself. To get the result, you should use await keyword:

bool result = await authentication();

You can read "What Happens in an Async Method" section of this MSDN article to get more understanding on async / await language feature.




回答2:


You need to await the task:

bool result = await authentication();

Or, you can use your favourite alternate method of waiting on a Task.



来源:https://stackoverflow.com/questions/23272911/is-it-possible-to-use-taskbool-in-if-conditions

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!