简体   繁体   中英

Nested async methods... do I need to await?

Let's say I have an existing async method returning a Task that runs well. It awaits and is itself awaited properly. This method takes an int argument:

public async Task<MyType> MyMethod(int foo)
{
    // .. do stuff 
}

We want to update this method to instead accept a string, and if we can parse an int from the string, then do what we've always done (moved to a new helper method), otherwise, if we can parse a Guid, then a call a different (but very similar) method. If neither type will parse, then return an empty/noop result:

public async Task<MyType> MyMethod(string foo)
{
    if ( int.TryParse(foo, out int bar))
    {
        return MyIntHelper(bar);
    }
    else if (Guid.TryParse(foo, out Guid bar))
    {
        return MyGuidHelper(bar);
    }
    else return MyNoop();
}

private async Task<MyType> MyIntHelper(int foo)
{
    // original ".. do stuff" here
}

private async Task<MyType> MyGuidHelper(Guid foo)
{
    // similar ".. do stuff" here, but using a Guid instead
}

The question is, in the updated MyMethod() , do I need to await the results of the helper methods, or since I'm already returning a Task and any necessary awaiting is still in the caller and child methods am I already covered?

As some background, this is in the context of updating a controller to accept an additional "endpoint", but really I'd like to decouple the question from that context as much as possible.

in the updated MyMethod(), do I need to await the results of the helper methods

If you use async , then you should use await . As a general rule, you should use async and await for most asynchronous methods.

Anytime you have nontrivial logic (including the possibility of exceptions), you should use async and await . For trivial method implementations, you canelide async and await (as described on my blog).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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