.NET Development - Calling a subroutine asynchronously and waiting for the response, part II

A couple of days ago, I wrote an article that showed how to run code asynchronously.

http://dyndeveloper.com/articleview.aspx?ArticleID=255

That worked as advertised, but I've since gotten the requirement to report to the user on the progress. That method won't work so well, so I developed some code using the BackgroundWorker class that does the trick.

Here's the requirement: Write a Windows form that calls a class, the class does some work that takes a while (in this case, integrating files into Dynamics). Report back to the main form periodically and allow the user to see the progress.

In our example we use a list box to report, because it's quick and easy.

 

 

Related Articles

... and you 'll find more on the NET Development Menu

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 Int16ByVal 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.ObjectByVal e As DoWorkEventArgsHandles 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.ObjectByVal e As ProgressChangedEventArgsHandles 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.ObjectByVal e As RunWorkerCompletedEventArgsHandles 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

 


RealWorldCode gives developers practical, real‑world solutions with clean, working code — no fluff, no theory, just answers.
Links
Home
Knowledge Areas
Sitemap
Contact
Et cetera
Privacy Policy
Terms and Conditions
Cookie Preferences