I have a windows forms app, on click of button I want to loop a list of integers and make http post calls in such a way that only 50 parallel requests can be made per second. This is because the target http endpoint only supports 50 requests per second. To achieve this here is my logic:
I have declared the SemaphoreSlim throttler as a global variable:
var throttler = new SemaphoreSlim(50);
In the button click event, I am looping over a list of items and making http calls:
List<Task> lstTasks = new List<Task>();
foreach (var item in lstItems)
{
lstTasks.Add(CallAsyncMtd(item));
}
The method that makes the http calls is:
private async Task CallAsyncMtd(int item, IProgress<int> progress)
{
await throttler.WaitAsync(); // here I am doing an async wait for the semaphore so that not more than 5 threads can run at the same time
try
{
await Task.Delay(1000).ConfigureAwait(false); //simulate an api call, configure await is false so the remaining code will run on separate thread
}
catch (Exception e)
{
//do some exception handling
}
//saveResponseToMySQL(response) //save the http response to mysql database synchronously
progress.Report(1); //report progress
await Task.Delay(1000 * 1); //wait for 1 second
throttler.Release(); //release semaphore
}
I am waiting for 1 second (in a separate thread) after making the request. Is there any better way so that I can make 50 requests per second without having to wait an additional second as per above logic?