RottenCheese
RottenCheese

Reputation: 949

Task vs async Task

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.

Upvotes: 22

Views: 19220

Answers (3)

erhan355
erhan355

Reputation: 1086

Async methods are different than normal methods. Whatever you return from async methods are wrapped in a Task. If you return no value(void) it will be wrapped in Task, If you return int it will be wrapped in Task and so on. Same question : async await return Task

Upvotes: 0

sonicbhoc
sonicbhoc

Reputation: 443

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.

Upvotes: 10

nlawalker
nlawalker

Reputation: 6514

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.

Upvotes: 15

Related Questions