C# WebClient DownloadFileAsync-如何向用户显示下载速度?

C# WebClient DownloadFileAsync-如何向用户显示下载速度?,c#,webclient,C#,Webclient,这几乎是标题中的全部问题。我有一个WPF C#Windows应用程序,我为用户下载文件,现在想显示速度。使用 当您连接WebClient时,您可以订阅ProgressChanged事件,例如 _httpClient = new WebClient(); _httpClient.DownloadProgressChanged += DownloadProgressChanged; _httpClient.DownloadFileCompleted += DownloadFileCompleted;

这几乎是标题中的全部问题。我有一个WPF C#Windows应用程序,我为用户下载文件,现在想显示速度。

使用


当您连接WebClient时,您可以订阅ProgressChanged事件,例如

_httpClient = new WebClient();
_httpClient.DownloadProgressChanged += DownloadProgressChanged;
_httpClient.DownloadFileCompleted += DownloadFileCompleted;
_httpClient.DownloadFileAsync(new Uri(_internalState.Uri), _downloadFile.FullName);
此处理程序的EventArgs为您提供BytesReceived和TotalBytesToReceive。使用此信息,您应该能够确定下载速度并相应地拍摄进度条

mWebClient.DownloadProgressChanged += (sender, e) => progressChanged(e.BytesReceived);
//...
DateTime lastUpdate;
long lastBytes = 0;

private void progressChanged(long bytes)
{
    if (lastBytes == 0)
    {
        lastUpdate = DateTime.Now;
        lastBytes = bytes;
        return;
    }

    var now = DateTime.Now;
    var timeSpan = now - lastUpdate;
    var bytesChange = bytes - lastBytes;
    var bytesPerSecond = bytesChange / timeSpan.Seconds;

    lastBytes = bytes;
    lastUpdate = now;
}

使用bytesPerSecond变量执行任何需要的操作。

我们可以通过确定下载开始后经过的秒数轻松完成此操作。我们可以将总秒数除以接收到的秒数,得到速度。看看下面的代码

DateTime _startedAt;

WebClient webClient = new WebClient();

webClient.DownloadProgressChanged += OnDownloadProgressChanged;

webClient.DownloadFileAsync(new Uri("Download URL"), "Download Path")

private void OnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    if (_startedAt == default(DateTime))
    {
        _startedAt = DateTime.Now;
    }
    else
    {
        var timeSpan = DateTime.Now - _startedAt;
        if (timeSpan.TotalSeconds > 0)
        {
            var bytesPerSecond = e.BytesReceived / (long) timeSpan.TotalSeconds;
        }
    }
}

@努内斯帕斯卡尔:还没有,我看不到任何适用的事件,我真的不知道从哪里开始。当上次更新在同一秒内时,则timeSpan。秒数为0,这将导致被零除。
DateTime _startedAt;

WebClient webClient = new WebClient();

webClient.DownloadProgressChanged += OnDownloadProgressChanged;

webClient.DownloadFileAsync(new Uri("Download URL"), "Download Path")

private void OnDownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
    if (_startedAt == default(DateTime))
    {
        _startedAt = DateTime.Now;
    }
    else
    {
        var timeSpan = DateTime.Now - _startedAt;
        if (timeSpan.TotalSeconds > 0)
        {
            var bytesPerSecond = e.BytesReceived / (long) timeSpan.TotalSeconds;
        }
    }
}