Normally, methods written async do not run faster than sync methods and only allow the system to respond to more requests. This topic was presented in the article How Thread pool works. Also on sharplab.io you can see the code written in async.

 In this article we want to remove extra async / await in the code. Consider the scenario of reading information from the database, typically we have a controller and a service. Which is read async within the data service. But there is no need to write the desired action async in the controller. Consider the following code:

public class TagService : ITagService
{
    private readonly ApplicationDbContext _context;

    public TagService(ApplicationDbContext context)
    {
        _context = context;
    }
    public async Task<IEnumerable<Tags>> GetTagsAsync(CancellationToken cancellationToken)
    {
        return await _context.Tags.ToListAsync(cancellationToken);
    }
}

The GetTagsAsync method is written async and includes async and await. And controller code:

[Route("api/[controller]")]
[ApiController]
public class TagController : ControllerBase
{
    private readonly ITagService _tagService;

    public TagController(ITagService tagService)
    {
        _tagService = tagService;
    }
    [HttpGet]
    public async Task<IEnumerable<Tags>> Get(CancellationToken cancellationToken)
    {
        return await _tagService.GetTagsAsync(cancellationToken);
    }
}

In the controller, the method of receiving tags is written async, which is not needed and we can rewrite it as follows:

[HttpGet]
public Task<IEnumerable<Tags>> Get(CancellationToken cancellationToken)
{
    return _tagService.GetTagsAsync(cancellationToken);
}

In case you have an async method and when you call this method and you do not need its return value, as in the example above, you can delete the async / await field. But if you need the value after calling the method, you should use async / await, as in the following example:

[HttpGet]
public async Task<IEnumerable<Tags>> Get(CancellationToken cancellationToken)
{
    var tags = await _tagService.GetTagsAsync(cancellationToken);
    var validTags = tags.Where(a => a.IsValid).ToList();
    return validTags;
}

In the above code, to create the conditions that require async / await, we have filtered the tags that are valid after receiving them from the service.

Related posts:

;)

Powered by Froala Editor

Comments