In case there is a requirement to limit requests to third party APIs, instead of invoking all tasks into tasks array and awaiting them all, it’s possible to use SemaphoreSlim and ConcurrentDictionary.
Limit thread count on client Link to heading
var semaphore =
new SemaphoreSlim(initialCount: 30, maxCount: 30);
var requestsList = ... // List with some params for API
// ApiResponse is from refit
var apiResponses = new ConcurrentDictionary<string, ApiResponse<POCO>>();
var lookupTasks = requestsList.Select(async request =>
{
await semaphore.WaitAsync();
try
{
// _api -> some api service dependecy
var response = await _api.Get(request);
apiResponses.TryAdd(request, response);
}
finally
{
semaphore.Release();
}
});
await Task.WhenAll(lookupTasks);
Set rate limiter on API endpoint Link to heading
- Use AspNetCoreRateLimit
- Use System.Threading.RateLimiting .NET 7
Links: .NET Rate Limiter in .NET 7 Announcing Rate Limiting for .NET