【发布时间】:2011-11-04 10:13:40
【问题描述】:
我想将下载速度计算为 kbps(每秒 kb)。代码有问题,它没有显示实际速度。我真的厌倦了这项工作。此外,当使用(TotalDownloadSize / ElapsedTime) 公式时,它会显示更真实的结果,但您知道它会得到平均值,这将是愚蠢的。
它通常给出 4000,基本上是因为块 4096,当我将它设置为 128 时,我得到 50/100/125 值。
DateTime dlElapsed;
private delegate void UpdateProgessCallback(Int64 BytesRead, Int64 TotalBytes, Int32 CurrentBytes);
private void UpdateProgress(Int64 BytesRead, Int64 TotalBytes, Int32 CurrentBytes)
{
DateTime Elapsed = DateTime.Now;
var progress = Convert.ToInt32((BytesRead * 100) / TotalBytes);
var elaps = (Elapsed - dlElapsed).TotalSeconds;
long kbps;
if (elaps > 0)
{
kbps = Convert.ToInt64((CurrentBytes / elaps) / 1024);
updateLabelText(String.Format("Downloading ({0} kbps)...", kbps));
}
// Make progress on the progress bar
if (progress < progressBar1.Maximum)
{
progressBar1.Value = progress;
}
else
{
progressBar1.Value = progressBar1.Maximum;
}
dlElapsed = DateTime.Now;
}
private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
// Some stuff here...
int byteSize = 0;
byte[] downBuffer = new byte[4096];
FileStream strLocal= new FileStream(path, FileMode.Create, FileAccess.Write);
dlElapsed = DateTime.Now;
while ((byteSize = stream.Read(downBuffer, 0, downBuffer.Length)) > 0)
{
strLocal.Write(downBuffer, 0, byteSize);
this.Invoke(new UpdateProgessCallback(this.UpdateProgress),
new object[] { strLocal.Length, totalbyte, byteSize});
}
updateLabelText("Download complete!");
strLocal.Close();
}
}
那么问题出在哪里?
【问题讨论】:
-
强制漫画:xkcd.com/612
-
并注意:后台工作人员已经有一个 ProgressChanged 事件,没有理由自己进行回调。如果你这样做了,看看 BeginInvoke()。
-
我见过的大多数“当前速度”测量结果似乎显示“迄今为止的平均速度”(到目前为止的总下载大小除以迄今为止的总经过时间)。
-
我想实时进行。
-
嗯,实时 == 不准确
标签: c# networking download