3

我有一堂课正在阅读 http 流文件。

    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);
        }
    }

假设我并行下载 5 个文件(运行此类的 5 个实例)并且我希望总比特率<800 kb/s

我很难计算延迟 x。任何帮助表示赞赏。

4

1 回答 1

2
double downloadDurationInSec = ...; //provide this
long bytesTransferred = ...; //provide this
double targetBytesPerSec = 800 * 1000;
double targetDurationInSec = bytesTransferred / targetBytesPerSec;
if (targetDurationInSec < downloadDurationInSec) {
 double sleepTimeInSec = downloadDurationInSec - targetDurationInSec;
 Thread.Sleep(TimeSpan.FromSeconds(sleepTimeInSec));
}

请注意包含单位的富有表现力的变量命名。

该算法的想法是计算下载到当前点应该花费多长时间。如果它比应有的速度快,那就睡个大觉吧。

这在数值上是稳定的,因为您不会增量更新任何变量。

于 2013-12-16T17:59:17.887 回答