This works well however I am wondering if using tasks is the best solution here? Would using async/await be a better idea and more accepted way?
Yes, absolutely. Doing parallel processing on ASP.NET consumes multiple threads per request, which can severely impact your scalability. Asynchronous processing is far superior for I/O.
To use async, first start with your lowest-level call, somewhere inside your service. It’s probably doing an HTTP call at some point; change that to use asynchronous HTTP calls (e.g., HttpClient). Then let async grow naturally from there.
Eventually, you’ll end up with asynchronous getdata1Async, getdata2Async, and getdata3Async methods, which can be consumed concurrently as such:
[HttpGet]
public async Task<IActionResult> myControllerAction()
{
var t1 = service.getdata1Async();
var t2 = service.getdata2Async();
var t3 = service.getdata3Async();
await Task.WhenAll(t1, t2, t3);
var data = new returnObject
{
d1 = await t1,
d2 = await t2,
d3 = await t3
};
return Ok(data);
}
With this approach, while the three service calls are in progress, myControllerAction uses zero threads instead of four.