【发布时间】:2012-07-17 12:36:11
【问题描述】:
这几乎就是标题中的全部问题。我有一个 WPF C# Windows 应用程序,我为用户下载文件,现在想显示速度。
【问题讨论】:
-
@nunespascal:还没有,我看不到任何适用的事件,不知道从哪里开始。
这几乎就是标题中的全部问题。我有一个 WPF C# Windows 应用程序,我为用户下载文件,现在想显示速度。
【问题讨论】:
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 变量做任何你需要的事情。
【讨论】:
我们可以通过确定下载开始后经过了多少秒来轻松做到这一点。我们可以将 BytesReceived 值从总秒数中除以得到速度。看看下面的代码。
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;
}
}
}
【讨论】:
使用DownloadProgressChanged event
WebClient client = new WebClient ();
Uri uri = new Uri(address);
// Specify that the DownloadFileCallback method gets called
// when the download completes.
client.DownloadFileCompleted += new AsyncCompletedEventHandler (DownloadFileCallback2);
// Specify a progress notification handler.
client.DownloadProgressChanged += new DownloadProgressChangedEventHandler(DownloadProgressCallback);
client.DownloadFileAsync (uri, "serverdata.txt");
private static void DownloadProgressCallback(object sender, DownloadProgressChangedEventArgs e)
{
// Displays the operation identifier, and the transfer progress.
Console.WriteLine("{0} downloaded {1} of {2} bytes. {3} % complete...",
(string)e.UserState,
e.BytesReceived,
e.TotalBytesToReceive,
e.ProgressPercentage);
}
【讨论】:
当你连接 WebClient 时,你可以订阅 ProgressChanged 事件,例如
_httpClient = new WebClient();
_httpClient.DownloadProgressChanged += DownloadProgressChanged;
_httpClient.DownloadFileCompleted += DownloadFileCompleted;
_httpClient.DownloadFileAsync(new Uri(_internalState.Uri), _downloadFile.FullName);
此处理程序的 EventArgs 为您提供 BytesReceieved 和 TotalBytesToReceive。使用此信息,您应该能够确定下载速度并相应地拍摄进度条。
【讨论】: