Are we need to use async/await keyword in controller?

Viewed 238

I have a user controller like this:

public class UserController : ControllerBase
{
    private readonly IUserService _userService;

    public UserController(IUserService userService)
    {
        _userService = userService;
    }
    public async Task<User> Get(int id, CancellationToken cancellationToken)
    {
        return await _userService.GetUserById(id, cancellationToken);
    }
}

and a user service:

public class UserService : IUserService
{
    public async Task<User> GetUserById(int id, CancellationToken cancellationToken)
    {
        return await _dbContext.Users.Where(a => a.Id == id).FirstOrDefaultAsync(cancellationToken);
    }
}

In UserService i have an async method that return a user by Id.

My question is, do we need to use async/await keyword in controller or using async/await in UserService is enough?

public class UserController : ControllerBase
{
    private readonly IUserService _userService;

    public UserController(IUserService userService)
    {
        _userService = userService;
    }
    public Task<User> Get(int id, CancellationToken cancellationToken)
    {
        return _userService.GetUserById(id, cancellationToken);
    }
}
2 Answers

If you're only awaiting one thing, as the last line of an async method, and returning the result directly or not at all (i.e. not doing anything non-trivial with the result), then yes you can elide the await, by removing the async and await parts; this avoids a bit of machinery, but it means that if the method you're calling faults synchronously (specifically: it throws an exception rather than returning a task that reports a fault state), then the exception will surface slightly differently.

Avoiding this state machine can matter if you're in an inner loop, for example in the middle of IO code that gets called many many times per operation and you need to optimize it, but: that doesn't apply here - you're at the top of a controller. Honestly, it doesn't need optimizing: just use the async/await: it'll be more consistently correct.

Related