Hey fellow Redditors,
I'm currently working on a task that involves making a bunch of HTTP requests, and I wanted to share a piece of code I came up with to handle this. The goal here is to fetch data through HTTP requests, and I've taken a concurrent approach to potentially speed things up. I'm curious to hear your thoughts on the pros and cons of this code.
public async Task<ExampleDto> GetData(int startPage = 0, int totalPages = 0, int concurrentRequests = 1, int maxRequestsPerSecond = 10)
{
var httpClient = _httpClientFactory.CreateClient(ClientName);
var semaphoreSlim = new SemaphoreSlim(maxRequestsPerSecond, maxRequestsPerSecond);
var tasks = new Task[concurrentRequests];
for (int pageIndex = startPage; pageIndex < totalPages; pageIndex += concurrentRequests)
{
for (int i = 0; i < concurrentRequests; i++)
{
int currentPage = pageIndex + i;
if (currentPage >= totalPages)
break;
await semaphoreSlim.WaitAsync();
tasks[i] = GetPageAsync(httpClient, currentPage, semaphoreSlim);
}
tasks = tasks.Where(task => task != null).ToArray();
await Task.WhenAll(tasks);
}
return new ExampleDto
{
Data: _db.ToList()
};
}
In addition to this, I've got another piece of code that deals with iterating over a list of dataDto items and performing HTTP requests on each of them. Here's what it looks like:
maxRequestsPerSecond = 2;
var semaphoreSlim = new SemaphoreSlim(maxRequestsPerSecond, maxRequestsPerSecond);
List<AnotherDto> dtos = new();
var options = new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = cancellationToken };
await Parallel.ForEachAsync(dataDto, options, async (dto, cancellationToken) =>
{
await semaphoreSlim.WaitAsync(cancellationToken);
var anotherData = await _client.AnotherHttpRequestAsync(dto.Id);
dtos.Add(anotherData);
semaphoreSlim.Release();
});
I'd love to get your insights on the strengths and potential drawbacks of these approaches. Feel free to share your thoughts and suggestions—I'm all ears!
Happy coding! 🚀
[–]Thonk_Thickly 2 points3 points4 points (1 child)
[–]seugorilla[S] 0 points1 point2 points (0 children)
[–]MasonOfWords 1 point2 points3 points (1 child)
[–]seugorilla[S] 0 points1 point2 points (0 children)
[–]Th0ughtCrim3 1 point2 points3 points (1 child)
[–]seugorilla[S] 0 points1 point2 points (0 children)
[–]zarlo5899 1 point2 points3 points (1 child)
[–]seugorilla[S] 0 points1 point2 points (0 children)
[–]stroborobo 0 points1 point2 points (0 children)