私は現在、定義された数のサンプルを取得して、定義された期間の平均ダウンロード速度を計算するクラスを作成しています。これが機能すると私が思ったのは、このクラスが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 {...}
}