1

Is it necessary to await every time I use something async or can I await it once after multiple async methods?

Can I skip using await in the repository since I'm awaiting in the consumer?

public class SomethingRepository : ISomethingRepository
{
    private readonly DbSet<Something> _dbSet;
    
    public SomethingRepostory(ApplicationContext ctx)
    {
        _dbSet = ctx.Set<Listing>();
    }

    // Should it be like variant 1?
    public Task<List<Something>> GetAsyncVariant1()
    {
        return _dbSet.ToListAsync();
    }

    // Or like variant 2 with async/await?
    public async Task<List<Something>> GetAsyncVariant2()
    {
        return await _dbSet.ToListAsync();
    }
}
// Usage in consumer
var data = await _somethingRepository.GetAsync();
justpen
  • 178
  • 1
  • 11
  • This questions has been answered by many people and the answer quite often depends on who you ask and what your use case is. You should however know what the consequences are when you use one over the other. See [Eliding Async Await - Stephen Cleary](https://blog.stephencleary.com/2016/12/eliding-async-await.html) and [David Fowler -Prefer asnyc/ await over directly returning Task](https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AsyncGuidance.md#prefer-asyncawait-over-directly-returning-task). Also see [this Github issue](https://github.com/dotnet/docs/issues/16187). – Mushroomator Apr 12 '23 at 12:56

1 Answers1

-2

Cleary has a good post about this "Eliding Async and Await" https://blog.stephencleary.com/2016/12/eliding-async-await.html

It's definitely a little more efficient to just return the task if it's a one liner. Though in this case I'd try to use IAsyncEnumerable for the return type if it's possible

Ready Cent
  • 1,821
  • 3
  • 18
  • 25