I\'m writing a utility that will be uploading a bunch of files, and would like to provide the option to rate limit uploads. What is the best approach for rate limiting uploa
Implementing speed limit is relatively easy, take a look at the following snippet:
const int OneSecond = 1000;
int SpeedLimit = 1024; // Speed limit 1kib/s
int Transmitted = 0;
Stopwatch Watch = new Stopwatch();
Watch.Start();
while(...)
{
// Your send logic, which return BytesTransmitted
Transmitted += BytesTransmitted;
// Check moment speed every five second, you can choose any value
int Elapsed = (int)Watch.ElapsedMilliseconds;
if (Elapsed > 5000)
{
int ExpectedTransmit = SpeedLimit * Elapsed / OneSecond;
int TransmitDelta = Transmitted - ExpectedTransmit;
// Speed limit exceeded, put thread into sleep
if (TransmitDelta > 0)
Thread.Wait(TransmitDelta * OneSecond / SpeedLimit);
Transmitted = 0;
Watch.Reset();
}
}
Watch.Stop();
This is draft untested code, but I think it is enough to get the main idea.