我建議不同的東西:你很可能使用DateTime.Now速度給定的開始時間的百分比,它的下載正在算?
Imports System.Net
Public Class Form1
Private tmp = IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.Temp, "snafu.fubar")
Private Downloading As Boolean = False
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Downloading Then Exit Sub
Downloading = True
Dim wc As New WebClient
AddHandler wc.DownloadProgressChanged, AddressOf wc_ProgressChanged
AddHandler wc.DownloadFileCompleted, AddressOf wc_DownloadDone
wc.DownloadFileAsync(New Uri("http://cachefly.cachefly.net/100mb.test"), tmp, Stopwatch.StartNew)
End Sub
Private Sub wc_DownloadDone(sender As Object, e As System.ComponentModel.AsyncCompletedEventArgs)
Downloading = False
End Sub
Private Sub wc_ProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs)
Me.Label1.Text = (e.BytesReceived/(DirectCast(e.UserState, Stopwatch).ElapsedMilliseconds/1000.0#)).ToString("#")
End Sub
End Class
因爲它沒有任何意義由接收的字節最後一個塊以確定的速度,而是你衡量字節由總時間的總數和鴻溝。將秒錶實例傳遞給事件處理程序具有以下優點:它不會損壞您的類代碼 - 僅在需要的地方纔可見。
謝謝您的回覆。我在哪裏分配這個活動? 'client.DownloadProgressChanged + = Function(sender,e)progressChanged(e.BytesReceived)' – Scott
AddHandler client.DownloadProgressChanged,Sub(s,ee) ProgressChanged(ee.BytesReceived) End Sub - - 聲明您的WebClient變量。 – Ric
@Ric錯誤'聲明期望結束.'然後出現 – Scott