I was wondering if my approach is good to query a REST-API in parallel because there is a limit on how many results can be obtained with one request (1000). To speed up things I want to do this in parallel.
The idea is to use a partitioner to create a set of ranges (10 ranges in my case). Every range is executed in parallel to query an API-endpoint.
The result is array of Tasks. With Task.WhenAll(tasks)
I wait until all tasks have been finished and then I have to flatten down the string[][]
-array to get a one dimensional array.
Any ideas or a better solution?
public async Task<string[]> QueryApiAsParallel() {
int maximum = 10000; // I don't want to query more than 10000 results,
// even I know that are a lot more results
int rangeSize = 1000; // maximum number that can be received via API
Task<string[]>[] tasks = Partitioner.Create(0, maximum, rangeSize).AsParallel()
.Select(async (range, index) => {
int skip = range.Item1;
int first = range.Item2 - range.Item1;
string[] names = await apiClient.GetNames(skip, first);
return names;
}).ToArray();
string[][] tasksCompleted = await Task.WhenAll(tasks);
string[] flattened = tasksCompleted.SelectMany(x => x).ToArray();
return flattened;
}
The implementation is maybe a bit inefficient.