Created
September 18, 2019 02:22
-
-
Save changhuixu/b45b22c55cd3dac6c94b32b3846cdda7 to your computer and use it in GitHub Desktop.
.net core named httpclient, throttle rate, semaphore, semaphoreslim, task, async, asynchronous,
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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