I have a class reading a http stream file.
static long CurrentMilliseconds { get { return Environment.TickCount; } }
public void ReadFile()
{
...
while(true)
{
int r = stm.Read(buf, 0, bufSize);
if(r == 0) break;
...
int x= CalculateDelay()
Thread.Sleep(x);
}
}
Let's say I download 5 files in parallel (5 instances of this class running) and I want total bitrate<800 kb/s
I have difficulty calculating delay x. Any help appreciated.
Note the expressive variable naming which includes the units.
The idea of the algorithm is to calculate how long the download should have taken up to the current point. If it was faster than it should have, sleep the difference.
This is numerically stable because you don't incrementally update any variables.