public class SpeedLimit
{
private const int BalancerUp = 50;
private const int BalancerDown = -75;
private double _CurrentWait;
private bool _Enabled;
private double _MaxLimit;
private OperationListControl _OperationListControl = null;
public Func<double> CalcRate = null;
public SpeedLimit()
{ }
public void SetOperationListControl(OperationListControl control)
{
this._OperationListControl = control;
}
public double MaxLimit
{
get { return this._MaxLimit; }
set
{
this._MaxLimit = value;
if (this._MaxLimit == 0)
this._Enabled = false;
else
this._Enabled = true;
}
}
public void WaitFor()
{
if (this._Enabled && this._OperationListControl != null && this.CalcRate != null)
{
double totalRate = this.CalcRate();
if (totalRate > this._MaxLimit)
{
this._CurrentWait += BalancerUp;
}
else
{
this._CurrentWait = Math.Max(this._CurrentWait + BalancerDown, 0);
}
Thread.Sleep((int)this._CurrentWait);
Debug.WriteLine("TotalDownloadRate = " + totalRate);
Debug.WriteLine("maxLimit = " + this._MaxLimit);
Debug.WriteLine("currentWait = " + this._CurrentWait);
}
}
}