0

I am trying to understand how to write async controllers in webapi. Below is an example, I fake a 5 sec work in DB.

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private readonly ILogger<WeatherForecastController> _logger;

    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }

    [HttpGet(Name = "GetWeatherForecast")]
    public async Task<int> Get()
    {
        var r = new ServiceLayer();
        var res = r.getDataAsync(_logger);
        var res2 = r.getDataAsync(_logger);

        var val = await res;
        var val2 = await res2;

        _logger.Log(LogLevel.Error, "UNDER");
        
        return val+val2;
    }
}

public class ServiceLayer
{
    public Task<int> getDataAsync(ILogger<WeatherForecastController> _logger)
    {
        var a = new DAtaBaseLayer();
        return a.queryAsync(_logger);
    }
}

public class DAtaBaseLayer
{
    public Task<int> queryAsync(ILogger<WeatherForecastController> _logger)
    {
        var t = new Task<int>(() =>
        {
            _logger.Log(LogLevel.Error, "BEFORE");
            Thread.Sleep(5555);
            _logger.Log(LogLevel.Error, "AFTER");
            return 77;
        });
        t.Start();
        return t;
    }
}

I am a bit confused what would be the difference if I let the ServiceLayer be async too. What benefit would I get? Is this idiomatic? Should it then not be called getDataAsync but instead getData?

public class ServiceLayer
{
    public async Task<int> getDataAsync(ILogger<WeatherForecastController> _logger)
    {
        var a = new DAtaBaseLayer();
        return await a.queryAsync(_logger);
    }
}
Theodor Zoulias
  • 34,835
  • 7
  • 69
  • 104
klundby
  • 301
  • 1
  • 3
  • 17
  • 2
    `Thread.Sleep` is not the correct way to fake asynchronous work; it blocks the thread. You should use `await Task.Delay` instead which is non-blocking. – Johnathan Barclay Dec 02 '21 at 15:43
  • 2
    Also, [don't use the `Task` constructors](https://blog.stephencleary.com/2014/05/a-tour-of-task-part-1-constructors.html). – Johnathan Barclay Dec 02 '21 at 15:44

0 Answers0