Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
.net core named httpclient, throttle rate, semaphore, semaphoreslim, task, async, asynchronous,
public class ThrottledHttpClient : IThrottledHttpClient
{
private readonly HttpClient _httpClient;
private readonly string _baseUrl = @"http://localhost:5000/api";
public ThrottledHttpClient(HttpClient httpClient)
{
_httpClient = httpClient;
}
public async Task<PrimeNumberResult[]> GetPrimeNumberResults(
List<long> numbers,
int requestLimit = 2,
int limitingPeriodInSeconds = 1)
{
var throttler = new SemaphoreSlim(requestLimit);
var tasks = numbers.Select(async n =>
{
await throttler.WaitAsync();
var task = _httpClient.GetStringAsync($"{_baseUrl}/values/isPrime?number={n}");
_ = task.ContinueWith(async s =>
{
await Task.Delay(1000 * limitingPeriodInSeconds);
Console.WriteLine($"\t\t {n} waiting");
throttler.Release();
});
try
{
var isPrime = await task;
Console.WriteLine($"{n}");
return new PrimeNumberResult(n, isPrime);
}
catch (HttpRequestException)
{
Console.WriteLine($"\t\t\t {n} error out");
return new PrimeNumberResult(n, "NA");
}
});
return await Task.WhenAll(tasks);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.