Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 returns a user by Id.

My question is, do we need to use async/await keyword in controller or is using async/await in UserService 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);
    }
}
like image 588
Farhad Zamani Avatar asked Nov 01 '25 21:11

Farhad Zamani


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

like image 90
Marc Gravell Avatar answered Nov 03 '25 12:11

Marc Gravell