I am not entirely new to using async/await in C#, but certainly have not done a ton of it by any means. I am looking to find out how much async code to write based on a certain scenario. The scenario is as follows:
.NET Core Web Api with controller and one async Get()
function:
[ApiController]
[Route("api/[controller]")]
public class ThingController
{
private readonly IThingFetchService _thingFetchService;
public ThingController(IThingFetchService thingFetchService)
{
_thingFetchService = thingFetchService;
}
public async Task<ActionResult<ThingSummary>> Get()
{
return await _thingFetchService.GetDataAsync();
}
}
Here is the call into the service layer (IThingFetchService):
public class ThingFetchService : IThingFetchService
{
private readonly IApiDataFetcher _dataFetcher;
private readonly IChartDetailBuilder _chartDetailBuilder;
public ThingFetchService(IApiDataFetcher dataFetcher, IChartDetailBuilder chartDetailBuilder)
{
_dataFetcher = dataFetcher;
_chartDetailBuilder = chartDetailBuilder;
}
public async Task<ThingSummary> GetDataAsync()
{
var things = await _dataFetcher.GetDataAsync<Thing>(); // returns IEnumerable<Thing> from an external API
// NOTE: THIS IS WHAT THE QUESTION IS ABOUT:
// Should this call be async, even though it is just crunching the data already fetched? (i.e. no I/O or anything, just processing
// and crunching data into new data points for a chart)
var chartDetails = _chartDetailBuilder.GetChartDetails(things);
return new ThingSummary {
Things = things,
ChartDetails = chartDetails
}
}
}
And just for full reference, the service that gets called that the question is all about:
public class ChartDetailBuilder : IChartDetailBuilder {
// should this be async?
public IEnumerable<ChartDetail> GetChartDetails(IEnumerable<Thing> things) {
var details = new List<ChartDetail>();
foreach(var thing in things) {
// do something sort of tedious, potentially intensive to get a data point from a Thing object
details.Add(new ChartDetail {
X = 1,
Y = 1
});
}
return details;
}
}
Long story short here: I want to know if the IChartDetailBuilder.GetChartDetails(IEnumerable<Thing> things)
method should be async or not or if it matters in the context of being called from an async method? I guess I am specifically looking at this in the context of .NET Web API but any feedback is genuinely appreciated.