使用C#下载器的下载速率

时间:2014-10-21 12:59:15

标签: c# winforms webclient-download

我想在我的下载器中实现下载速率。谷歌搜索后发现了一个相当复杂的应用Download manager - limit download speed。然后,在另一个线程https://stackoverflow.com/questions/26073779/how-to-add-download-rate-and-limit-rate-in-downloader-in-c-sharp找到了一个很好的建议:

  

设置一个每秒触发的计时器,并使用计数器记录已下载的字节数,在计时器Tick事件中将下载速率报告为x Bytes / s,同时将计数器重置为零

使用

开始实现此功能
bytesIn = int.Parse(e.BytesReceived.ToString());
totalBytes = int.Parse(e.TotalBytesToReceive.ToString());

我的代码中有bytesIn显示已接收到的字节但是如何使用定时器实现上面引用的建议,就好像我使用tick()事件并在每个tick()事件上计算它不会告诉我我的速度。

建议吗?

1 个答案:

答案 0 :(得分:0)

您需要做的是在计时器中记录bytesIn并存储以供日后使用。下次计时器触发(一秒钟后),您将获取新的bytesIn值,然后减去之前的值。这将获得在最后一秒下载的字节数。您可以在屏幕上将此数字显示为#### Bytes/s,您也可以将该数字除以1024,并将结果显示为#### Kbytes/s

long lastDownload = 0;
long bytesIn = 0

//This is a event for a timer that fires once per second on the UI thread.
private void TimerTick(object sender, EventArgs e)
{
     //Figure out how many bytes where downloaded in the last second.
     var bytesDownloadedLastSecond = bytesIn - lastsDownload;

     //Copy the number over for the next firing of TimerTick.
     lastDownload = bytesIn;


     double scalingFactor;    
     string formatText;

     //Figure out if we should display in bytes, kilobytes or megabytes per second.
     if(bytesDownloadedLastSecond < 1024)
     {
          formatText = "{0:N0} B/sec";
          scalingFactor = 1;
     }
     else if(bytesDownloadedLastSecond < 1024 * 1024)
     {
          formatText = "{0:N2} Kb/sec";
          scalingFactor = 1024;
     }
     else
     {
          formatText = "{0:N2} Mb/sec";
          scalingFactor = 1024 * 1024;
     }

     //Display the speed to the user, scaled to the correct size.
     speedTextBox.Text = String.Format(formatText, bytesDownloadedLastSecond / scalingFactor );
}

private void DownloadProgress(object sender, EventArgs e)
{
    bytesIn = int.Parse(e.BytesReceived.ToString());
    totalBytes = int.Parse(e.TotalBytesToReceive.ToString());
}