简体   繁体   中英

Do I have to use async/await in all methods in call API chain?

I was wondering how to implement Dapper Asynchronously. I found this

Looks cool, but I noticed that there are used async/await in all methods in that call api chain:

Controller:

[HttpGet]
[Route("dob/{dateOfBirth}")]
public async Task<ActionResult<List<Employee>>> GetByID(DateTime dateOfBirth)
{
    return await _employeeRepo.GetByDateOfBirth(dateOfBirth);
}

Repository:

public async Task<List<Employee>> GetByDateOfBirth(DateTime dateOfBirth)
{
    using (IDbConnection conn = Connection)
    {
        string sQuery = "SELECT ID, FirstName, LastName, DateOfBirth FROM Employee WHERE DateOfBirth = @DateOfBirth";
        conn.Open();
        var result = await conn.QueryAsync<Employee>(sQuery, new { DateOfBirth = dateOfBirth });
        return result.ToList();
    }
}

So if we would have more layers between, like service etc. then those layers should also have async/await? I think it is redundant and is totally enough to have async/await in place where is method that really returns asynchronous result. In other places like Controller, Services - only Task is required.

Exception can be place where we have using block that would dispose the whole context. So there we have to have async/await also.

Am I right, or I miss something?


@EDIT

So controller could be saved as:

[HttpGet]
[Route("dob/{dateOfBirth}")]
public Task<ActionResult<List<Employee>>> GetByID(DateTime dateOfBirth)
{
    return _employeeRepo.GetByDateOfBirth(dateOfBirth);
}

As you see I removed async/await - now only repository has async/await and the result and performance should be the same, right?

... - only Task is required.

Yes. But under the condition that you only have one async call and that that is the last statement in your method. The GetByDateOfBirth() method does not qualify because of the ToList() coming after the await .

It's called "eliding the async and await keywords" and it is a small optimization.

I usually don't bother to remove them. Having predictable, readable and modification-safe code is more important. Also, await helps with converting pesty co- and contra-variant return types.

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