异步下载多个文件 VB.net

Downloading multiple files async VB.net

我正在为我的 Minecraft 服务器上的 mod 创建一个 installer/updater。我将其设置为有两个文件,每行一个 mod,代码比较这两个文件,如果不匹配则下载最新的 mod。目前我有这样的下载设置:

        For x = 2 To latestModCount - 1
            If currentModList(x) <> latestModList(x) Then
                IO.File.Delete(applicationLocation & "multimc\instances\Dan's Server\minecraft\mods\" & currentModList(x))
                My.Computer.Network.DownloadFile(OnlineFiles & "mods/" & latestModList(x), _
                        applicationLocation & "multimc\instances\Dan's Server\minecraft\mods\" & latestModList(x))
            End If

            'Updates currentModList to = latestModList
            objWriter.Write(latestModList(x))
        Next

使用此方法,表单在下载文件时完全冻结。

我想要的是在每次下载时都有一个进度条移动,每次完成新的下载时重置为零。我知道使用 this 方法我可以下载一个文件,并且进度条会很好地移动。但是,这个问题是因为它使用异步下载,上面代码下面的任何代码都在下载完成之前执行,这在尝试解压缩不存在的 zip 文件时成为问题。

如果有人有解决方案,请提供代码示例,因为这实际上是我用任何语言编写的第一个程序,教程除外。

使用 WebClient.DownloadFileAsync 并在 client_DownloadCompleted 中处理完成的下载。

伪代码:

Private i as Integer = -1

Private Sub StartNextDownload()
    Do
        i++
    Loop Until currentModList(i) <> latestModList(i)
    If i < latestModCount Then
        IO.File.Delete(applicationLocation & "multimc\instances\Dan's Server\minecraft\mods\" & currentModList(i))
        Dim client As WebClient = New WebClient
        AddHandler client.DownloadProgressChanged, AddressOf client_ProgressChanged
        AddHandler client.DownloadFileCompleted, AddressOf client_DownloadCompleted
        client.DownloadFileAsync(New Uri(OnlineFiles & "mods/" & latestModList(i)), applicationLocation & "multimc\instances\Dan's Server\minecraft\mods\" & latestModList(i))
    End If
End Sub

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())
End Sub

Private Sub client_DownloadCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.AsyncCompletedEventArgs)
    HandleCompletedDownload() 'unzip and other stuffs there
    StartNextDownload()
End Sub

另一种方法是一次触发所有下载,类似于您当前的下载(同样,在 client_DownloadCompleted 中处理完成的下载)。但是,在这种方法中,您要么根本不使用进度条,要么进行一些对初学者不友好的编程来跟踪 individual/total 下载的进度。