目的是在标签4上计算和显示下载速度。
private void Download()
{
using (var client = new WebClient())
{
client.DownloadFileCompleted += (s, e) => label1.Text = "Download file completed.";
client.DownloadProgressChanged += (s, e) => progressBar1.Value = e.ProgressPercentage;
client.DownloadProgressChanged += (s, e) => label2.Text = FormatBytes(e.BytesReceived);
client.DownloadProgressChanged += (s, e) => label4.Text = e.
client.DownloadProgressChanged += (s, e) =>
{
label3.Text = "%" + e.ProgressPercentage.ToString();
label3.Left = Math.Min(
(int)(progressBar1.Left + e.ProgressPercentage / 100f * progressBar1.Width),
progressBar1.Width - label3.Width
);
};
client.DownloadFileAsync(new Uri("https://speed.hetzner.de/10GB.bin"), @"d:\10GB.bin");
}
}
在标签4的行处,我想显示速度。
client.DownloadProgressChanged += (s, e) => label4.Text = e.
发布于 2021-10-11 08:18:45
正如@AKX所建议的那样,Stopwatch
类帮助您在下载文件时计算每秒接收的字节数。
在类范围内创建字段(基于WPF应用程序的示例):
public partial class MainWindow : Window
{
private readonly System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
}
初始化WebClient
(最简单的方式)时,创建两个处理程序:WebClient.DownloadProgressChanged
事件和WebClient.DownloadFileCompleted
事件。然后,在您调用WebClient.DownloadFileAsync()
之前,调用stopwatch.Start()
开始测量时间。
using (System.Net.WebClient wc = new System.Net.WebClient())
{
wc.DownloadProgressChanged += OnDownloadProgressChange;
wc.DownloadFileCompleted += OnDownloadFileComplete;
stopwatch.Start(); // Start the Stopwatch
wc.DownloadFileAsync(downloadLink, fileName); // Run file download asynchroniously
}
在DownloadProgressChanged
事件处理程序中,可以结合DownloadProgressChangedEventArgs
的BytesReceived
属性和Stopwatch
的Elapsed.TotalSeconds
属性来获得下载速度:
private void OnDownloadProgressChange(object sender, System.Net.DownloadProgressChangedEventArgs e)
{
// Calculate progress values
string downloadSpeed = string.Format("{0} MB/s", (e.BytesReceived / 1024.0 / 1024.0 / stopwatch.Elapsed.TotalSeconds).ToString("0.00"));
}
我将BytesReceived
除以两次到1024,以获得MB而不是Bytes的值,但您可以随意选择。另外,我将结果值格式化为0.00
(例如,获取“1.23MB/s”)。如果需要,还可以为您的目的计算和格式化其他DownloadProgressChangedEventArgs
属性。
最后,在WebClient.DownloadFileCompleted
事件处理程序中,您应该重置Stopwatch
以停止它,并为其他新下载重置其测量的时间:
private void OnDownloadFileComplete(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
stopwatch.Reset();
}
完整的版本可能如下所示(MainWindow.cs
):
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private readonly System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
private void BtnDownloadFile_Click(object sender, RoutedEventArgs e)
{
Uri downloadLink = new Uri("https://speed.hetzner.de/100MB.bin");
string fileName = "H:\\100MB.bin";
btnDownloadFile.IsEnabled = false; // Disable to prevent multiple runs
using (System.Net.WebClient wc = new System.Net.WebClient())
{
wc.DownloadProgressChanged += OnDownloadProgressChange;
wc.DownloadFileCompleted += OnDownloadFileComplete;
stopwatch.Start();
wc.DownloadFileAsync(downloadLink, fileName);
}
}
private void OnDownloadProgressChange(object sender, System.Net.DownloadProgressChangedEventArgs e)
{
// Calculate progress values
string downloadProgress = e.ProgressPercentage + "%";
string downloadSpeed = string.Format("{0} MB/s", (e.BytesReceived / 1024.0 / 1024.0 / stopwatch.Elapsed.TotalSeconds).ToString("0.00"));
string downloadedMBs = Math.Round(e.BytesReceived / 1024.0 / 1024.0) + " MB";
string totalMBs = Math.Round(e.TotalBytesToReceive / 1024.0 / 1024.0) + " MB";
// Format progress string
string progress = $"{downloadedMBs}/{totalMBs} ({downloadProgress}) @ {downloadSpeed}"; // 10 MB / 100 MB (10%) @ 1.23 MB/s
// Set values to contols
lblProgress.Content = progress;
progBar.Value = e.ProgressPercentage;
}
private void OnDownloadFileComplete(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
lblProgress.Content = "Download complete!";
stopwatch.Reset();
btnDownloadFile.IsEnabled = true; // Restore arailability of download button
}
}
XAML:
<Grid>
<StackPanel HorizontalAlignment="Stretch"
VerticalAlignment="Center">
<Label x:Name="lblProgress"
Content="Here would be progress text"
Margin="10,0,10,5"
HorizontalContentAlignment="Center"/>
<ProgressBar x:Name="progBar"
Height="20"
Margin="10,0,10,5" />
<Button x:Name="btnDownloadFile"
Content="Download file"
Width="175"
Height="32"
Click="BtnDownloadFile_Click"/>
</StackPanel>
</Grid>
它将是什么样子:
https://stackoverflow.com/questions/69518725
复制相似问题