I'm rather new to C#, and found relevant subclassing examples surprisingly hard to come by. I've whipped up this class that appears to work, but am pretty sure this is not optimal:
private class ThrottledRestClient
{
int pause; // mininum ms between requests
double rpm; // max requests per minute
long last_request_time;
RestClient client;
public ThrottledRestClient(string url, HttpBasicAuthenticator auth, double rpm = 60)
{
this.client = new RestClient(url);
this.client.Authenticator = auth;
this.rpm = rpm;
this.pause = (int)((60 / rpm) * 1000);
}
public IRestResponse Execute(RestRequest request)
{
long now = DateTime.Now.Ticks;
int wait = pause - (int)((now - this.last_request_time) / TimeSpan.TicksPerMillisecond);
if (wait > 0)
{
//Console.WriteLine("Waiting ms: " + wait);
Thread.Sleep(wait);
}
this.last_request_time = DateTime.Now.Ticks;
return this.client.Execute(request);
}
}
How could this be better? Is there an existing solution I haven't found?