【问题标题】:Downloading multiple files async VB.net异步下载多个文件 VB.net
【发布时间】:2015-02-07 13:21:35
【问题描述】:

我正在为我的 Minecraft 服务器上的模组创建安装程序/更新程序。我已经将它设置为有两个文件,每行一个 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 文件时会成为问题。

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

【问题讨论】:

标签: vb.net asynchronous


【解决方案1】:

使用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 中处理已完成的下载)。但是,在这种方法中,您要么根本不使用进度条,要么进行一些对初学者不友好的编程来跟踪单个/总下载的进度。

【讨论】:

  • 感谢您的回复。但是,我仍然不明白如何使用例如 for 循环来做到这一点。你能把这段代码放到我的代码中吗?我最终想要的是让用户通知正在下载文件,最好不要锁定 GUI。
  • @DanielShields 编辑了我的代码。调用 StartNextDownload 开始。我现在没有visual studio,有些事情取决于你自己的代码,所以不要指望它仅仅通过复制粘贴就能工作。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多