Harsha
Harsha

Reputation: 569

How to wait for BackgroundWorker finish without getting the UI Freeze

I'm trying to code a simple file downloader. There are 4 or more files need to download one by one. I have used a backgroundWorker to avoid freeze the UI. And I have sent the first URL through a variable.

    Dim  crrDownloading as String
    dim URL1  as String = "https://example.com/download/file1.zip"
    dim URL2  as String = "https://example.com/download/file2.zip"
    dim URL3  as String = "https://example.com/download/file3.zip"
    dim URL4  as String = "https://example.com/download/file4.zip"    

Private Sub DownloadList()

    'Download 1st File
     StartDownload(URL1)

    'Download 2nd File
     StartDownload(URL2)

     ...

End Sub

Private Sub StartDownload(URL)

    If Not bwDownloader.IsBusy Then
            crrDownloading = URL
            bwDownloader.RunWorkerAsync()
    End If

End Sub


Private Sub bwDownloader_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles bwDownloader.DoWork
    'web request code...

    theRequest = WebRequest.Create(crrDownloading)

    'more code...
End Sub

I want to download the next files after the backgroundworkerdownload the current file. What is the correct way to wait for the backgroundworker to finish there task?

Upvotes: 1

Views: 138

Answers (1)

jmcilhinney
jmcilhinney

Reputation: 54417

It's good to understand what's actually happening here. The BackgroundWorker isn't downloading any files. All the BackgroundWorker does is raise an event on a background thread. It's up to you to handle that event and then any code you put in your event handler is executed on that background thread. The event handler in your code is part of your form, so it's your form that's downloading the files, not the BackgroundWorker.

If you were going to stick with the BackgroundWorker then you would have two choices. Either you would download the files in serial, one after the other, or else you would download them in parallel, which would require one BackgroundWorker per file. Using multiple BackgroundWorkers is a little cumbersome, but the good thing is that you can use the same method to handle all the DoWork events. You would just pass in the URL when you call RunWorkerAsync. If you just use one BackgroundWorker then you would write a method that performs one download and then call that four times.

That said, it probably is better to go with the Task option suggested in the comments.

Upvotes: 2

Related Questions