I created several different classes that include BackgroundWorker. I usually use the BackgroundWorker component in a form that will open when the task is completed, and then pass this instance to the constructor of my work class.
Here's what your work class looks like:
Private m_bwMain As BackgroundWorker Public Sub New(ByVal bwMain As BackgroundWorker) m_bwMain = bwMain 'additional setup code here End Sub
To start the task, you will do something similar in the Click event handler of the Download button:
lblStatus.Text = "Initializing ..." bgwMain.RunWorkerAsync(someFileName)
I declare my work class as a private member of the current form, and then create an instance in the BackgroundWorker.DoWork event. From there, you can call your method to download the file:
Private Sub bgwMain_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgwMain.DoWork m_oJobEngine = New JobEngine(CType(sender, BackgroundWorker)) m_oJobEngine.DownloadFile(CStr(e.Argument)) End Sub
To report progress to the user, you can handle the events raised by your class in your main form. You just need to make sure the job class object declaration has the WithEvents keyword. From these handlers, you can call the ReportProgress BackgroundWorker method. From ReportProgress, you can make any changes you need for the user interface to indicate progress. Here is an example:
Private Sub m_oJobEngine.DownloadProgress(ByVal bgw as Backgroundworker, ByVal bytesTransferred as Long) Handles m_oJobEngine.DownloadProgress bgw.ReportProgress(0, bytesTransferred) End Sub Private Sub bgwMain_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgwMain.ProgressChanged lblStatus.Text = CLng(e.UserState).ToString & " bytes transferred." End Sub
Hope this helps.
source share