Hello,
I'm having some trouble while downloading files async.
I have the following code:
Then, I have the following code:Code:Private Sub DownLoadFileAsync(address As String, path As String) Dim client As Net.WebClient = New Net.WebClient() AddHandler client.DownloadDataCompleted, Sub(sender As Object, e As System.Net.DownloadDataCompletedEventArgs) RaiseEvent OnDownloadCompleted(e.Result) End Sub AddHandler client.DownloadProgressChanged, Sub(sender As Object, e As System.Net.DownloadProgressChangedEventArgs) RaiseEvent OnDownloadProgress(e.ProgressPercentage) Application.DoEvents() End Sub Dim uri As Uri = New Uri(address) client.DownloadFileAsync(uri, path) End Sub
I'm consuming an API that downloads some files. It could 5, it could be 300, one at a time. My UI frozes while the downloads are made, so it's not making it async.Code:MetroSetProgressBar1.Value = 0 AddHandler Me.OnDownloadProgress, Sub(percet As Integer) MetroSetProgressBar1.Value = percet End Sub AddHandler Me.OnDownloadCompleted, Sub(data() As Byte) MetroSetProgressBar1.Value = 100 End Sub Dim selected As String = MetroSetListBox1.Items(MetroSetListBox1.SelectedIndex()).ToString() Dim splited() As String = selected.Split(" - ") Dim card As String = MetroSetListBox2.Items(MetroSetListBox2.SelectedIndex()).ToString() Dim cardsplit() As String = card.Split(" - ") Dim uriString As String = "API URL" Dim Request As HttpWebRequest = WebRequest.Create(New Uri(uriString)) Dim JSON_Response As String = New StreamReader(Request.GetResponse().GetResponseStream()).ReadToEnd() Dim JSON_Obj1 As Object = New JavaScriptSerializer().DeserializeObject(JSON_Response) Dim Test1 As String = JSON_Obj1("image")("png").ToString() Dim savePathimg As String = MetroSetTextBox1.Text & splited(0) & "\" & cardsplit(0) & ".png" Dim savePath As String = MetroSetTextBox1.Text & splited(0) If (Not System.IO.Directory.Exists(savePath)) Then If My.Settings.create_folder = 1 Then System.IO.Directory.CreateDirectory(savePath) Dim download As New WebClient() AddHandler download.DownloadProgressChanged, AddressOf Download_ProgressChanged 'download.DownloadFileAsync(New Uri(Test1), savePathimg) DownLoadFileAsync(Test1, savePathimg) If My.Settings.open_location = 1 Then Process.Start("explorer.exe", savePath) End If Else MetroSetMessageBox.Show(Me, "Folder " & savePath & " does not exists. Please create it or go to options.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Error) End If Else Dim download As New WebClient() AddHandler download.DownloadProgressChanged, AddressOf Download_ProgressChanged download.DownloadFileAsync(New Uri(Test1), savePathimg) If My.Settings.open_location = 1 Then Process.Start("explorer.exe", savePath) End If End If
So, what I'm doing wrong?
Also, how can I make this to wait X seconds between each download without frozing my UI?
Thanks




Reply With Quote
