I have a lot of requests to send to a server (Amazon Product Advertising API), however this server doesn't allow me to send more than 1 request each second. I am looking for a free solution, based on C# abilities.
I tried to code it like this:
public static WebResponse Request(Dictionary<string, string> parameters) {
var response = LaunchRequest(parameters);
Sleep(1000);
return response;
}
The problem is that multiple threads are entering in the method "Request" at the same time. If there are 4 threads, then there will be 4 requests per second.
How can my threads wait each other ?
EDIT: I tried with a lock.
So I wrote this code :
public class RequestHandler {
private static readonly RequestHandler instance = new RequestHandler();
private Object thisLock = new Object();
private RequestHandler() { }
public static RequestHandler Instance {
get {
return instance;
}
}
public WebResponse Request(Dictionary<string, string> parameters) {
lock (thisLock) {
Log();
var response = LaunchRequest(parameters);
Sleep(1000);
return response;
}
}
}
So I call my method like this :
// ...
RequestHandler requestHandler = RequestHandler.Instance;
WebResponse response = requestHandler.Request(requestHelper, parameters);
// ...
It seems to work most of the time, but sometimes, my "LaunchRequest" method is fired almost at the same time.
EDIT 2: Here are the log results, the arrows are showing the calls where there is less than 1 second:
Request: 09:52:50.230 - Thread 22
Request: 09:52:48.830 - Thread 5
Request: 09:52:47.468 - Thread 10 <---
Request: 09:52:47.331 - Thread 13 <---
Request: 09:52:45.971 - Thread 12
Request: 09:52:44.767 - Thread 11
Request: 09:52:43.230 - Thread 5
Request: 09:52:30.546 - Thread 21 <---
Request: 09:52:30.357 - Thread 20 <---
Request: 09:52:29.232 - Thread 13
Request: 09:52:27.908 - Thread 11
Request: 09:52:26.471 - Thread 5
Request: 09:52:25.138 - Thread 11
Request: 09:52:23.835 - Thread 12