How to use throttled API without restriction?

I am trying to figure out how to use an API that has a maximum of 5 requests per second, without limitation. If the request reaches the limit, I get an error message from the API. Thread.Sleep (200) does not seem to be the right solution, since I need efficiency.

foreach (Foo foo in fooList) { try { // Max 5 API calls per second! How? ThirdPartyResponse response = ContactThirdPartyApi(foo); // do something with response ... } } 

Preferably, I would like to use some background workers for calls, but how can I control the number of requests per second? I tried to consider, for example, Hangfire in order to solve this problem, but actually it does not work for this type of restriction.

How can I submit a request and know when I get a response, it should be possible to keep track of how many were dismissed and completed, and to make sure that no more than 5 per second. But how? Any suggestions are welcome!

+5
source share
1 answer

You can limit the number of simultaneous requests using Semaphore or SemaphoreSlim , you will need to add a time element when it will be released.

Joel Fillmore wrote an implementation of TimeSpanSemaphoreSlim , which you could include in the implementation of the API. IIRC, I successfully combined it with RestSharp for a previous project.

You might want to change the implementation a bit to correctly set the Thread.Sleep(1) permission .

+4
source

Source: https://habr.com/ru/post/1203068/


All Articles