我尝试编写应用程序来下载2个文件,我可以使用以下代码下载2个文件:
Dim client As WebClient = New WebClient
AddHandler client.DownloadProgressChanged, AddressOf client_ProgressChanged
AddHandler client.DownloadFileCompleted, AddressOf client_DownloadCompleted
client.DownloadFileAsync(New Uri("http://URL.com/Myfile.exe"), "..\MyFile.exe")
Button1.Text = "Download in Progress"
Button1.Enabled = False
Dim client2 As WebClient = New WebClient
AddHandler client2.DownloadProgressChanged, AddressOf client_ProgressChanged
AddHandler client2.DownloadFileCompleted, AddressOf client_DownloadCompleted
client2.DownloadFileAsync(New Uri("http://URL.com/Myfile2.exe"), "..\MyFile2.exe")
我遇到的问题是进度条没有显示两个文件的总下载进度。它会显示一个,然后几秒钟后会显示另一个并继续在两者之间切换。
Private Sub client_ProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
Dim bytesIn As Double = Double.Parse(e.BytesReceived.ToString())
Dim totalBytes As Double = Double.Parse(e.TotalBytesToReceive.ToString())
Dim percentage As Double = bytesIn / totalBytes * 100
ProgressBar.Value = Int32.Parse(Math.Truncate(percentage).ToString())
Label1.Text = "Downloaded: " & bytesIn & " of " & totalBytes
Label2.Text = String.Format("{0:00}", percentage) & "%"
End Sub
任何人都知道如何让进度条结合两个下载的值?或者也许我可以告诉它等待第一次下载然后开始第二次?
答案 0 :(得分:3)
您只需跟踪每个WebClient的进度。总进展将达到200%。解决一般情况:
Dim progress As Dictionary(Of WebClient, Integer)
Sub StartDownloads()
progress = new Dictionary(Of WebClient, Integer)
Dim client As WebClient = New WebClient()
progress.Add(client, 0)
'' etc..
End Sub
Private Sub client_ProgressChanged(ByVal sender As Object, ByVal e As DownloadProgressChangedEventArgs)
progress(DirectCast(sender, WebClient)) = e.ProgressProcent
Dim total As Integer = 0
For Each client In progress.Keys
total += progress(client)
Next
ProgressBar.Value = total \ progress.Count
End Sub
未经测试,应该接近。
答案 1 :(得分:1)
要使其一次加载一个文件,请对所有文件名使用List(Of String)
。使用第一个元素(文件名)启动该过程使用已完成的事件,并删除该文件名和已完成事件的addhandler。然后检查List(Of String)
中是否有更多文件,然后为该网络充电新的WebClient - 冲洗重复。
Private files As New List(Of String)
'fill this with the file names(URIs) then start the process
Private Sub DownloadFile()
Dim client As New WebClient
AddHandler client.DownloadProgressChanged, AddressOf client_ProgressChanged
AddHandler client.DownloadFileCompleted, AddressOf client_DownloadCompleted
client.DownloadFileAsync(New Uri(files(0), "some destination path")
End Sub
Private Sub client_DownloadCompleted(...)
RemoveHandler client.DownloadProgressChanged, AddressOf client_ProgressChanged
RemoveHandler client.DownloadFileCompleted, AddressOf client_DownloadCompleted
files.RemoveAt(0)
If files.Count > 0 Then DownloadFile()
End Sub