This is the calling form.
Public Class Form2
Private Sub startAsyncButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles startAsyncButton.Click
'this is the class that is going to do the work
Dim oWork2 As New Work2
'subscribe to the delegate that will report notifications
oWork2.NotifyStatusChanged = AddressOf HandleNotifications
Me.Enabled = False
'start the work
oWork2.StartWork()
End Sub
Sub HandleNotifications(intPercent As Int16, strMessage As String)
'receive notification and display them to the user
Me.ListBox1.Items.Add(strMessage)
'scroll the list box to the bottom so the most recent item is visible
Me.ListBox1.TopIndex = Me.ListBox1.Items.Count - 8
If intPercent = 100 Then
Me.Enabled = True
End If
End Sub
End Class
This is the class that does the work
Imports System.ComponentModel
Public Class Work2
Dim WithEvents backgroundWorker1 As New BackgroundWorker
'declare a delegate
Public Delegate Sub StatusChanged(intPercent As Int16, ByVal strStatus As String)
'create a public instance of the delegate
Public NotifyStatusChanged As StatusChanged
Public Sub New()
'initialize the backgroundWorker object
backgroundWorker1.WorkerReportsProgress = True
backgroundWorker1.WorkerSupportsCancellation = False
End Sub
Sub StartWork()
If backgroundWorker1.IsBusy <> True Then
' Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync()
End If
End Sub
' This event handler is where the time-consuming work is done.
Private Sub backgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As DoWorkEventArgs) Handles backgroundWorker1.DoWork
Dim worker As BackgroundWorker = CType(sender, BackgroundWorker)
Dim i As Integer
For intFiles = 1 To 3
For i = 1 To 5
' Perform a time consuming operation and report progress.
System.Threading.Thread.Sleep(500)
'the first param is a percentage, we're not using that
'the second param is an object, we're storing a string there
worker.ReportProgress(1, String.Format("File {0}, Row {1}", intFiles, i))
Next
Next
End Sub
' This event handler updates the progress.
Private Sub backgroundWorker1_ProgressChanged(ByVal sender As System.Object, ByVal e As ProgressChangedEventArgs) Handles backgroundWorker1.ProgressChanged
'get the string stored in the ProgressChangedEventArgs and use the delegate to report it
NotifyStatusChanged.Invoke(e.ProgressPercentage, e.UserState)
End Sub
' This event handler deals with the results of the background operation.
Private Sub backgroundWorker1_RunWorkerCompleted(ByVal sender As System.Object, ByVal e As RunWorkerCompletedEventArgs) Handles backgroundWorker1.RunWorkerCompleted
Dim strStatus As String
If e.Cancelled = True Then
strStatus = "Canceled!"
ElseIf e.Error IsNot Nothing Then
strStatus = "Error: " & e.Error.Message
Else
strStatus = "Done!"
End If
'report a 100 percentage, this will trigger the form to enable
NotifyStatusChanged.Invoke(100, strStatus)
End Sub End Class