Returning Boolean Task from a Task
Today in this article, we shall see returning Boolean Task from a Task-based method. Here we will return bool from task i.e true or false from task-based operation.
Today in this article, we will cover below aspects,
Using Task<TResult> you can return boolean, int, or string depending on your requirements where the operand is TResult
. Here declaration must specify a return type of Task<bool>
or Task<int>
as required.
Async methods that don’t contain a return
statement usually have
a return type of Task. If a method returns Task, that means it’s the asynchronous version of a void
method.
Return Boolean from Task Asynchronously
Below an example for returning a boolean from Task asynchronously.
public async Task<bool> Delete(string key)
{
var isSuccess = false;
try
{
await _cache.RemoveAsync(key);
isSuccess = true;
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
return isSuccess;
}
return true;
}
Return Bool (True or False) from Task Synchronously
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.
Example
public Task<bool> DeleteCache(string key)
{
var isSuccess = false;
try
{
_cache.Remove(key);
isSuccess = true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return Task.FromResult(isSuccess);
}
return Task.FromResult(isSuccess); ;
}
Here above you determine when to send true or false using Task.FromResult() for the operation based on the custom validation.
References :
Do you have any comments or ideas or any better suggestions to share?
Please sound off your comments below.
Happy Coding !!
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.