首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何使用webclient计算和显示下载速度?

如何使用webclient计算和显示下载速度?
EN

Stack Overflow用户
提问于 2021-10-10 20:22:25
回答 1查看 623关注 0票数 2

目的是在标签4上计算和显示下载速度。

代码语言:javascript
运行
复制
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的行处,我想显示速度。

代码语言:javascript
运行
复制
client.DownloadProgressChanged += (s, e) => label4.Text = e.
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-10-11 08:18:45

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

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

代码语言:javascript
运行
复制
public partial class MainWindow : Window 
{
    private readonly System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
}

初始化WebClient (最简单的方式)时,创建两个处理程序:WebClient.DownloadProgressChanged事件和WebClient.DownloadFileCompleted事件。然后,在您调用WebClient.DownloadFileAsync()之前,调用stopwatch.Start()开始测量时间。

代码语言:javascript
运行
复制
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属性和StopwatchElapsed.TotalSeconds属性来获得下载速度:

代码语言:javascript
运行
复制
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以停止它,并为其他新下载重置其测量的时间:

代码语言:javascript
运行
复制
private void OnDownloadFileComplete(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
{
    stopwatch.Reset();
}

完整的版本可能如下所示(MainWindow.cs):

代码语言:javascript
运行
复制
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:

代码语言:javascript
运行
复制
<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>

它将是什么样子:

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69518725

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档