I am running a parallel.foreach loop to loop through a list. Each of the list items contains an identifier for an api, which I am accessing within the loop.
The api I am accessing can has a maximum of 225 requests per minute, so I would like to pause execution of the loop after 220 items and resume them again once the full minute has passed. I tried with Thread.sleep(numMilliSeconds), but it seems to start up a new thread for each one that goes to sleep or something of that nature.
This is roughly what I am working with now:
Parallel.ForEach(list, (currentItem) =>{
while(numRequestsLastMinute > 220 && DateTime.Now.Minute == lastDownloadTime.Minute)
{
var timeToPause = (60 - DateTime.Now.Second) * 1000;
Console.WriteLine("Thread pausing for" + timeToPause/100 + "seconds...");
Thread.Sleep(timeToPause);
Console.WriteLine("Thread resuming...");
}
if(DateTime.Now.Minute > lastDownloadTime.Minute)
{
lastDownloadTime = DateTime.Now;
numRequestsLastMinute = 0;
}
//send requests
}
Clearly, the Thread.Sleep is not the right way to go about this, but is there a similar construct I can use within a Parallel.Foreach loop?