Skip to content

Instantly share code, notes, and snippets.

@changhuixu
Created September 18, 2019 02:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save changhuixu/b45b22c55cd3dac6c94b32b3846cdda7 to your computer and use it in GitHub Desktop.
Save changhuixu/b45b22c55cd3dac6c94b32b3846cdda7 to your computer and use it in GitHub Desktop.
.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