Reputation: 137
This function gives an error:
[HttpPost]
public Task<IActionResult> Something (string value)
{
Student student = new Student();
if (value == "LOW")
{
return NotFound();
}
return Ok();
}
This function works fine:
[HttpPost]
public async Task<IActionResult> Something (string value)
{
Student student = new Student();
if (value == "LOW")
{
return NotFound();
}
return Ok();
}
When I am trying to return NotFound();
or return Ok();
when I am not including keyword asnyc
before Task
as shown above, it gives me error. However, when i added the async
keyword in front of Task
, it does not shows any error in the compiler. Can you tell me what is causing this?
Upvotes: 0
Views: 4914
Reputation: 218847
The async
keyword tells the compiler that while the method returns a Task
, the code within the method is expected to run in an asynchronous manner and internally await
something. The compiler will look for one or more await
s and modify the structure of the method to wrap functionality around tasks and continuations of tasks. So ultimately the compiler will wrap the returned result in a Task<T>
for you.
Basically, your logic can focus on the value you want to return, rather than focus on the structure of asynchronicity. The async
and await
keywords exist to make that part simpler.
So both of these methods actually have a problem:
async
, so the compiler isn't expecting to modify it in any way. Instead, the compiler is expecting it to return what it says it will return, which is a Task<IActionResult>
. It doesn't return that, so the compiler produces an error.async
, but nowhere in that method do you await
anything. The compiler can make this work, but produces a warning that nothing is being awaited in this async
method.So both are wrong. Since your method doesn't do anything asynchronous, don't make it async
:
[HttpPost]
public IActionResult Something(string value)
{
Student student = new Student();
if (value == "LOW")
{
return NotFound();
}
return Ok();
}
You only need to make the method async
(and wrap a Task<T>
around the return type) if the method internally needs to await
something.
Upvotes: 5
Reputation: 27862
If you do not want async...then your (first) code should be:
public IActionResult Something (string value)
(no Task)
Upvotes: 0