本文介绍了任务与异步任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我一直在试图弄清楚这一点,我读过一些文章,但没有一篇能提供我所寻找的答案.

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.

我的问题是:为什么 Task 必须返回一个Task,而 async Task 却不需要?例如:

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);
}

如您所见,该方法不是 async ,因此它必须返回一个Task.

As you can see there, that method isn't async, so it has to return a Task.

现在,看看这个:

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...
}

它使用 async 关键字,但不返回Task.这是为什么?我知道这可能是有史以来最愚蠢的问题.但我想知道为什么会这样.

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 指示编译器该方法包含 await .在这种情况下,您的方法隐式返回一个Task,因此您不需要这样做.

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.

这篇关于任务与异步任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 22:30