20

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;
}
Sergey Kolodiy
  • 5,829
  • 1
  • 36
  • 58
MohamedAbbas
  • 1,149
  • 4
  • 15
  • 31
  • 1
    No you can't use it directly since `Task` is not a `bool`. You should post the code you're actually having a problem with, but you can probably do `bool b = await authentication(); if(b) { ... }` – Lee Apr 24 '14 at 15:14
  • Your "async" authentication method doesn't await anything, so it's nto actually asynchronous – Servy Apr 24 '14 at 15:49

2 Answers2

38

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.

Sergey Kolodiy
  • 5,829
  • 1
  • 36
  • 58
1

You need to await the task:

bool result = await authentication();

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

Mike Caron
  • 14,351
  • 4
  • 49
  • 77
  • 1
    Using async/await choosing one of the "alternate methods" (`Task.Wait()` or `Task.Result`) can often lead to [deadlock situations](http://stackoverflow.com/questions/13140523/await-vs-task-wait-deadlock). – Scott Chamberlain Apr 24 '14 at 15:34