Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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;
}
like image 601
MohamedAbbas Avatar asked Apr 24 '14 15:04

MohamedAbbas


People also ask

How to return value for Task bool?

To return Boolean from Task Synchronously, we can use Task. FromResult<TResult>(TResult) Method. This method creates a Task result that's completed successfully with the specified result. The calling method uses an await operator to suspend the caller's completion till called async method has finished successfully.

How do I return a task object in C#?

The recommended return type of an asynchronous method in C# is Task. You should return Task<T> if you would like to write an asynchronous method that returns a value. If you would like to write an event handler, you can return void instead. Until C# 7.0 an asynchronous method could return Task, Task<T>, or void.

What does Task run do C#?

The Run method allows you to create and execute a task in a single method call and is a simpler alternative to the StartNew method. It creates a task with the following default values: Its cancellation token is CancellationToken.


2 Answers

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.

like image 80
Sergey Kolodiy Avatar answered Oct 10 '22 08:10

Sergey Kolodiy


You need to await the task:

bool result = await authentication();

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

like image 40
Mike Caron Avatar answered Oct 10 '22 08:10

Mike Caron