Ok, I've been trying to figure this out, I've read some articles but none of them provide the answer I'm looking for.
My question is: Why Task
has to return a Task whilst async Task
doesn't?
For example:
public override Task TokenEndpoint(OAuthTokenEndpointContext context)
{
// Code removed for brevity.
return Task.FromResult<object>(null);
}
As you can see there, that method isn't async
, so it has to return a Task.
Now, take a look at this one:
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
// Code removed for brevity...
if(user == null)
{
context.SetError("invalid_grant", "username_or_password_incorrect");
return;
}
if(!user.EmailConfirmed)
{
context.SetError("invalid_grant", "email_not_confirmed");
return;
}
// Code removed for brevity, no returns down here...
}
It uses the async
keyword, but it doesn't return a Task. Why is that?
I know this may be probably the stupidest question ever.
But I wanna know why it is like this.
Async methods are intended to be non-blocking operations. An await expression in an async method doesn't block the current thread while the awaited task is running. Instead, the expression signs up the rest of the method as a continuation and returns control to the caller of the async method.
The async keyword turns a method into an async method, which allows you to use the await keyword in its body. When the await keyword is applied, it suspends the calling method and yields control back to its caller until the awaited task is complete. await can only be used inside an async method.
NET, Task. Run is used to asynchronously execute CPU-bound code.
The Task asynchronous programming model (TAP) provides an abstraction over asynchronous code. You write code as a sequence of statements, just like always. You can read that code as though each statement completes before the next begins.
async
is an indicator to the compiler that the method contains an await
. When this is the case, your method implicitly returns a Task, so you don't need to.
The first method is not an asynchronous method. It returns a task, but by the time it returns the task, the entire method would have been done anyway.
The second method is asynchronous. Essentially, your code will execute synchronously until it reaches an await
keyword. Once it does, it will call the async
function and return control to the function that called it. Once the async
function returns its Task
, the awaited function resumes where it left off. There's more to it than that, and this was a relatively sparse answer.
However, the MSDN page on the async
keyword should help your understanding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With