多線程下載或上傳數據限速

直接上代碼吧

實際上就是做個偏移量,當速度大於指定速度時,增加Thread.Sleep的時間,小於時反之。

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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章