Using BackgroundWorker in VB.Net to update a datagrid

Updated on 08th December 2015

If you have time consuming operations such as extensive mathematical calculations, file or database operations on a large amount of data, etc., then the GUI can go unresponsive until that operation is completed. The .Net Framework's solution to this problem is the BackgroundWorker class.

BackgroundWorker class executes the time consuming operation on a separate background thread thereby keeping the GUI responsive to the end user. It can also report the progress of the operation periodically, cancel the operation while it is running and indicate when the operation is completed.

The following VB sample code demonstrates how to use the BackgroundWorker class to run an operation in the background. The time-consuming operation in this example is to import the contents of a CSV file to a data grid in VB.

First of all, Open Microsoft Visual Studio and create a new project of type Windows Forms Application

Drag and drop the following controls to the form and set their properties as below using the Properties window

ControlProperty NameProperty Value
Sample Form
Sample Form Layout

The purpose of this program is to import the contents of a CSV file, perform a simple calculation and update the data onto a data grid view control.

The Form Load event (Form1_load) sets two key properties of the Backgroundworker control -
WorkerSupportsCancellation property is set to True which allows the time consuming operation to be cancelled while it is running.
WorkerReportsProgress property is also set to True which allows screen to report the progress of the operation. Various other properties of the Data grid, Button and Label controls are also set during the form load event.

 'Allow background operation to be cancelled
   bgWorker.WorkerSupportsCancellation = True

 'Allow background operation to report progress
   bgWorker.WorkerReportsProgress = True

When the user clicks the Start button, the RunWorkerAsync method of background worker object is called. This method raises the DoWork event which executes the time consuming operation in the background.

 'Start time-consuming operation in background
 Call bgWorker.RunWorkerAsync()

If the user want to cancel the operation at anytime while it is running, he can do so by pressing the Stop button. In the Stop button click event you call the CancelAsync() property of background worker which sets the CancellationPending property to True.

'Stop background operation

In the DoWork event you need check if the user pressed the cancel button if not execute the backgrouns opeartion and report the progress. A basic framewor of DoWork event is shown below:

 Private Sub bgWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgWorker.DoWork
  If bgWorker.CancellationPending Then
     e.Cancel = True
     Exit Sub
   'Do some operation
   'Report the progress
    bgWorker.ReportProgress(percent, userstate)
  End if

End Sub

In the DoWork Event of this sample program we use a TextFieldParser object to read the contents of a csv file line by line. The progress of this background operation is reported after each line is read. This is achieved by calling the ReportProgress method of background worker object. In our program we have added some sleep after each line is read in order to simulate a time-consuming operation. The ReportProgress method inside DoWork raises the ProgressChanged event.

The ProgressChanged event execute the code that updates the rows that are read from the csv file to the datagrid. It also changes the value of the progress bar.

Private Sub bgWorker_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgWorker.ProgressChanged

 'Report the progress of background operation here

End Sub

Finally when all the lines of the csv file are read and the DoWork finish execution, the RunWorkerCompleted event is fired. This is where you do the clean-up such as disposing the TextFieldParser, enable/disable buttons, change messages etc.

 Private Sub bgWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles bgWorker.RunWorkerCompleted

 If e.Cancelled Or Not IsNothing(e.Error) Then
   'If the background opeartion was cancelled
   'or an error occured during execution then do something
 'If Background execution completed normally then do something else

 End If

End Sub

Program Source

Download BackgroundWorkerVB.txt


Datagrid update

Post a comment

Got a question about this article? Ask our forum


Your Comment

Email (We dont publish it)


Andre | June 17, 2017 1:51 PM |

Thanks for sharing this. I have to debug a project where this backgroundworker is been used and your article give me more confidend.