I have below method where, there is a call to a database in AppendExpandOption2DataAsync
& AppendExpandOption1DataAsync
if the ODataQuery options is passed and valid. However, the data that OData needs is returned by GetMyData
and thus the execution of AppendExpandOption2DataAsync
& AppendExpandOption1DataAsync
shoudl be hold until the GetData is returned, since GetData can also give a 500 or a 404. But my below approach is increasing latency as I am doing two DB calls. (1 for GetMyData & other for AppendExpandOption2DataAsync
or AppendExpandOption1DataAsync
). How can I optimize this code for minimal latency without changing its execution output.
public async Task<ResponseType> GetDataAsync(RequestType request, ODataQueryOptions<ResponseType>? options = null, string? version = null)
{
if (request == null) throw new ArgumentNullException(nameof(request));
try
{
// Verify expand options
IEnumerable<ExpandedNavigationSelectItem> expandOptions = options?.SelectExpand?.SelectExpandClause.SelectedItems.OfType<ExpandedNavigationSelectItem>();
(string identifierName, string identifierId) = Utils.GetIdentifier(request);
DataPreview dataPreview = await dataApiClient.GetMyData(identifierId, identifierName, version);
ResponseType response = dataPreview.ConvertToResponse();
List<Task> expandTasks = new List<Task>();
expandOptions?
.ToList()
.ForEach(item =>
{
if (item.PathToNavigationProperty.FirstSegment.Identifier.Equals("ExpandOption1", StringComparison.CurrentCultureIgnoreCase))
{
expandTasks.Add(AppendExpandOption1DataAsync(response));
}
else if (item.PathToNavigationProperty.FirstSegment.Identifier.Equals("ExpandOption2", StringComparison.CurrentCultureIgnoreCase))
{
expandTasks.Add(AppendExpandOption2DataAsync(response));
}
});
// Ensure all expand operations are completed
await Task.WhenAll(expandTasks);
return response;
}
}