目標是在下載時計算并在 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.
uj5u.com熱心網友回復:
正如@AKX建議的那樣,Stopwatch類可以幫助您計算下載檔案時每秒接收的位元組數。
在類范圍內創建一個欄位(基于 WPF 應用程式的示例):
public partial class MainWindow : Window
{
private readonly System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
}
初始化時WebClient(以最簡單的方式),創建 2 個處理程式:for WebClient.DownloadProgressChangedevent 和 for WebClient.DownloadFileCompletedevent。然后呼叫之前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's BytesReceivedproperty 和Stopwatch's Elapsed.TotalSecondsproperty 來獲得下載速度:
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>
看起來如何:

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/316215.html
上一篇:如何洗掉字串中的一塊
下一篇:統一的鍵盤映射
