Task vs async Task

余生颓废 提交于 2019-12-24 14:27:33

问题


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.


回答1:


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.




回答2:


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.




回答3:


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



来源:https://stackoverflow.com/questions/48392630/task-vs-async-task

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!