2016-01-10 125 views
-1

我創建了一個簡單的程序用於下載文件,下載第一組然後開始下載另一個並從列表中下載文件。 但有時會停在3檔並下載。 我調查過,即使文件下載到100%,以前的下載也沒有完成。BackgroundWorker不想停止工作

Private Sub Download(ByVal Down As Integer) 
    On Error Resume Next 
    Dim req As System.Net.WebRequest 
    Dim resp As System.Net.WebResponse 
    TextBox1.Text = Convert.ToString("http://example.com/files/" + Convert.ToString(Down) + ".zip") 
    TextBox2.Text = Convert.ToString(Down) 
    req = Net.WebRequest.Create(TextBox1.Text) 
    resp = req.GetResponse 
    req.Method = Net.WebRequestMethods.Http.Get 
    download_size = resp.ContentLength 
    ProgressBar1.Maximum = download_size 
    Console.WriteLine(BackgroundWorker1.IsBusy) 
    BackgroundWorker1.RunWorkerAsync() 
    Timer1.Start() 
End Sub 

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick 
    On Error Resume Next 
    downloaded_size = My.Computer.FileSystem.GetFileInfo(FlatTextBox1.Text + "\" + TextBox2.Text + ".zip").Length 
    ProgressBar1.Value = downloaded_size 
    If ProgressBar1.Value = ProgressBar1.Maximum Then 
     Timer1.Stop() 
     BackgroundWorker1.CancelAsync() 
     If Timer2.Enabled = False Then 
      Timer2.Start()'Timer 5sec to to start function Download(x) and ProgressBar set to 0 
     End If 
    End If 
End Sub 

Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork 
    On Error Resume Next 
    Console.WriteLine(TextBox1.Text + " | " + FlatTextBox1.Text + "\" + TextBox2.Text + ".zip") 
    My.Computer.Network.DownloadFile(TextBox1.Text, FlatTextBox1.Text + "\" + TextBox2.Text + ".zip", "", "", False, 360000, True) 

End Sub 
+2

只要您寫錯誤恢復下一代碼,您就無法獲得幫助。 –

+0

@HansPassant,我希望它是一個評論。 但是,它得到的原因,我已經上傳到服務器只有3個文件。 – Mubby

+0

我在任何地方評論了「On Error Resume Next」,並且當下載文件1,2或3時,它不會因錯誤而停止 - 只有4和較高(因爲我沒有上傳文件 - 404) – Mubby

回答

1

一種更好的方式來下載文件,比使用BackgroundWorker的是的WebClient與功能DownloadFileAsync。 但是必須在工具箱中啓用WebClient。

Private Sub Download(ByVal Down As Integer) 
    TextBox2.Text = Convert.ToString(Down) 
    Dim Adresa As String = "http://example.com/files/" + Convert.ToString(Down) + ".zip" 
    WebClient1.DownloadFileAsync(New Uri(Adresa), FlatTextBox1.Text + "\" + TextBox2.Text + ".zip") 
End Sub 

Private Sub WebClient1_DownloadProgressChanged(sender As Object, e As Net.DownloadProgressChangedEventArgs) Handles WebClient1.DownloadProgressChanged 
    ProgressBar1.Value = e.ProgressPercentage 
End Sub 

Private Sub WebClient1_DownloadFileCompleted(sender As Object, e As System.ComponentModel.AsyncCompletedEventArgs) Handles WebClient1.DownloadFileCompleted 
    ProgressBar1.Value = 0 
    'Here place script to download next file.. 
End Sub