Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats the difference with returning Task<bool> and just returning bool

Hopefully this is a nice and simple answer.

I'm using C# MVC Web API in ASP.NET Core 1. I'm creating web methods and I've seen examples with this of returning data.

Example 1:

public async Task<IActionResult> ExampleCall([FromBody]ExampleObj model)
{
     // Call some lower level function...
     var result = LowerLevelCall(model);
     return result;
}

And seen other examples like this.

Example 2:

public async Task<IActionResult> ExampleCall([FromBody]ExampleObj model)
{
     // Call some lower level function...
     var result = await LowerLevelCall(model);
     return result;
}

Main difference is that Example 2 using the await operator. What's the implications of implementing the await operator? Will this free resources up rather than waiting for code to complete in Example 1?

Thanks in advance for any tips!

like image 435
Rob McCabe Avatar asked Apr 25 '16 11:04

Rob McCabe


2 Answers

In your scenario, the async operator will stop the execution of the method until the result is received from LowerLevelCall. However when the execution of the method is stopped, await waits asynchronously so the thread itself is not blocked. After getting the result from LowerLevelCall the method just resumes executing synchronously.

Example 1 - If LowerLevelCall takes a long time to execute, you thread will be blocked and will just sit there and do nothing until the execution of LowerLevelCall is complete.

Example 2 - If you use await, you won't block the thread since await waits asynchronously. After LowerLevelCall finishes executing the result of the method will be assigned to your result variable.

Intro to Async And Await - This article should help you get started with async and await.

like image 190
Kerim Emurla Avatar answered Oct 13 '22 03:10

Kerim Emurla


In the first example if LowerLevelCall(model); takes a long time, your result won't be returned before this method finishes and this will block current thread - you have to wait all this time doing nothing.

In the second example current thread won't be blocked and you can do something other.You will get the result asynchronously when LowerLevelCall(model); finishes.

like image 45
Roman Doskoch Avatar answered Oct 13 '22 03:10

Roman Doskoch