PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197

PHP User Warning: fetch_template() calls should be replaced by the vB_Template class. Template name: bbcode_highlight in ..../includes/functions.php on line 4197
VS 2019 DownloadFileAsync not so Async-VBForums
Results 1 to 6 of 6

Thread: DownloadFileAsync not so Async

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Apr 2008
    Posts
    16

    DownloadFileAsync not so Async

    Hello,

    I'm having some trouble while downloading files async.

    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
    Then, I have the following code:
    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
    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.
    So, what I'm doing wrong?
    Also, how can I make this to wait X seconds between each download without frozing my UI?

    Thanks

  2. #2
    Superbly Moderated NeedSomeAnswers's Avatar
    Join Date
    Jun 2002
    Location
    Manchester uk
    Posts
    2,610

    Re: DownloadFileAsync not so Async

    Well your not awaiting your response, just calling the async method doesn't make it async unless you await the response

    Take a look at this https://docs.microsoft.com/en-us/dot...oncepts/async/
    Please Mark your Thread "Resolved", if the query is solved & Rate those who have helped you



  3. #3

    Thread Starter
    Junior Member
    Join Date
    Apr 2008
    Posts
    16

    Re: DownloadFileAsync not so Async

    I read the link you provided but got stuck. Can't transform my private sub into a task.
    I don't have so much knowledge in programming to make it work.

  4. #4
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    5,681

    Re: DownloadFileAsync not so Async

    vbnet Code:
    1. '
    2.     Async Private Function DownLoadFileAsync(address As String, path As String) as Task
    3.  
    4.         Dim client As Net.WebClient = New Net.WebClient()
    5.  
    6.         AddHandler client.DownloadDataCompleted, Sub(sender As Object, e As System.Net.DownloadDataCompletedEventArgs)
    7.                                                      RaiseEvent OnDownloadCompleted(e.Result)
    8.                                                  End Sub
    9.  
    10.         AddHandler client.DownloadProgressChanged, Sub(sender As Object, e As System.Net.DownloadProgressChangedEventArgs)
    11.                                                        RaiseEvent OnDownloadProgress(e.ProgressPercentage)
    12.                                                        Application.DoEvents()
    13.                                                    End Sub
    14.  
    15.         Dim uri As Uri = New Uri(address)
    16.         Await client.DownloadFileAsync(uri, path)
    17.     End Sub

    Note: I altered your code in plain text outside the IDE so no auto correct. I'm not sure if it's Async Private Function or Private Async Function but you can correct to suit. I still do most of my asynchronous stuff the old fashion way so I don't use this as much yet.

    Also, when you're using that make sure that whatever is calling that method is also using Await on the method.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena


    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. -jmcilhinney

  5. #5
    Lively Member
    Join Date
    Jun 2019
    Posts
    102

    Re: DownloadFileAsync not so Async

    Just to mention that System.Net.WebClient.DownloadFileAsync is not Async so it cannot be awaited:
    C# Code:
    1. public void DownloadFileAsync(Uri address, string fileName) =>
    2.      DownloadFileAsync(address, fileName, null);
    3.  
    4. public void DownloadFileAsync(Uri address, string fileName, object? userToken)
    5. {
    6. ...

    There is another function DownloadFileTaskAsync which returns Task and can be awaited.

  6. #6
    Frenzied Member
    Join Date
    Jul 2011
    Location
    UK
    Posts
    1,282

    Re: DownloadFileAsync not so Async

    I'd be very surprised if call(s) to DownLoadFileAsync caused the UI to freeze. I think the problem is much more likely to be found in code you haven't shown, or in the way you are using the code that you have shown here.

    You say you might download up to 300 images. So are you looping the second block of code? I ask because the lines:
    Code:
    Dim Request As HttpWebRequest = WebRequest.Create(New Uri(uriString))
    Dim JSON_Response As String = New StreamReader(Request.GetResponse().GetResponseStream()).ReadToEnd()
    are not Async, and will freeze the UI while the web request is negotiated and the JSON is downloaded from the server. Do that once and you'd hardly notice. Doing it 300 times in a loop however, would be a big problem.

    While running you code from the IDE, try pressing the pause button (or Debug menu/ Break All) at the point that the UI freezes. The line of code that is blocking execution or is part of a long running loop should be highlighted. Doesn't always work, but is worth a try.
    Last edited by Inferrd; Mar 27th, 2020 at 12:57 PM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width