gpt4 book ai didi

c# - 如何使用网络客户端计算和显示下载速度?

转载 作者:行者123 更新时间:2023-12-03 08:15:37 33 4
gpt4 key购买 nike

目标是在下载时计算并显示在label4.Text上的下载速度。

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");
}
}

在带有 label4.Text 的行我想显示速度。

client.DownloadProgressChanged += (s, e) => label4.Text = e.

最佳答案

正如@AKX所建议的,Stopwatch类可以帮助您计算下载文件时每秒接收的字节数。

在类范围内创建一个字段(基于 WPF 应用程序的示例):

public partial class MainWindow : Window 
{
private readonly System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
}

初始化 WebClient 时(最简单的方法),创建 2 个处理程序:用于 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 事件处理程序中,您可以组合 DownloadProgressChangedEventArgsBytesReceived 属性和 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 为单位的值,而不是字节,但您可以根据需要进行选择。另外,我将结果值格式化为 0.00 (例如,获得“1.23 MB/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>

它看起来如何:

enter image description here

关于c# - 如何使用网络客户端计算和显示下载速度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69518725/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com