我目前正在编写一个类来计算定义时间段内的平均下载速度,并采用定义数量的样本。我认为这可行的方式是,该类运行一个 Timer 对象,该对象调用所述类中的一个方法,该方法将查看下载的字节(维护在父类 FTPDownloadFile 中),然后将该样本存储在队列中。但是,我的问题是访问下载的字节数。
我访问该信息的方法是通过在构建下载计算类时传入的引用,但是,我似乎没有正确理解/使用引用。传入的变量总是显示为 0,即使我可以看到原始变量发生变化。
谁能告诉我我做错了什么/建议一个更好的方法让我完成我想做的事情?
首先,这是处理下载速度计算的类:
public class SpeedCalculator
{
private const int samples = 5;
private const int sampleRate = 1000; //In milliseconds
private int bytesDownloadedSinceLastQuery;
private System.Threading.Timer queryTimer;
private Queue<int> byteDeltas = new Queue<int>(samples);
private int _bytesDownloaded;
public SpeedCalculator(ref int bytesDownloaded)
{
_bytesDownloaded = bytesDownloaded;
}
public void StartPolling()
{
queryTimer = new System.Threading.Timer(this.QueryByteDelta, null, 0, sampleRate);
}
private void QueryByteDelta(object data)
{
if (byteDeltas.Count == samples)
{
byteDeltas.Dequeue();
}
byteDeltas.Enqueue(_bytesDownloaded - bytesDownloadedSinceLastQuery);
bytesDownloadedSinceLastQuery = _bytesDownloaded;
}
/// <summary>
/// Calculates the average download speed over a predefined sample size.
/// </summary>
/// <returns>The average speed in bytes per second.</returns>
public float GetDownloadSpeed()
{
float speed;
try
{
speed = (float)byteDeltas.Average() / ((float)sampleRate / 1000f);
}
catch {speed = 0f;}
return speed;
}
该类包含在我的 FTPDownloadFile 类中:
class FTPDownloadFile : IDisposable
{
private const int recvBufferSize = 2048;
public int bytesDownloaded;
public SpeedCalculator Speed;
private FileStream localFileStream;
FtpWebResponse ftpResponse;
Stream ftpStream;
FtpWebRequest ftpRequest;
public List<string> log = new List<string>();
private FileInfo destFile;
public event EventHandler ConnectionEstablished;
public FTPDownloadFile()
{
bytesDownloaded = 0;
Speed = new SpeedCalculator(ref bytesDownloaded);
}
public void GetFile(string host, string remoteFile, string user, string pass, string localFile)
{
//Some code to start the download...
Speed.StartPolling();
}
public class SpeedCalculator {...}
}