简体   繁体   English

任务与异步任务

[英]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?我的问题是:为什么Task必须返回 Task 而async Task没有? 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.正如您在那里看到的,该方法不是async ,因此它必须返回一个 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.它使用async关键字,但不返回任务。 Why is that?为什么? I know this may be probably the stupidest question ever.我知道这可能是有史以来最愚蠢的问题。 But I wanna know why it is like this.但我想知道为什么会这样。

async is an indicator to the compiler that the method contains an await . async是编译器的指示符,表明该方法包含await When this is the case, your method implicitly returns a Task, so you don't need to.在这种情况下,您的方法会隐式返回一个 Task,因此您不需要这样做。

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.本质上,您的代码将同步执行,直到到达await关键字。 Once it does, it will call the async function and return control to the function that called it.一旦这样做,它将调用async函数并将控制权返回给调用它的函数。 Once the async function returns its Task , the awaited function resumes where it left off.一旦async函数返回它的Task ,等待的函数就会从它停止的地方恢复。 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.但是,有关async关键字的MSDN 页面应该有助于您理解。

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.如果没有返回值(void),它将被包装在 Task 中,如果您返回 int 它将被包装在 Task 中,依此类推。 Same question : async await return Task同样的问题: 异步等待返回任务

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM