VB.NET BackgroundWorker - Update ProgressBar With Cancellation

Today we have a go at a simple threading example with VB.NET. We work with BackgroundWorker class and update a progress barĀ  and percentage while simulating a background operation.Our example with support cancellation,by which we reset our progress bar.

Public Class Form1

    'DO HEAVY WORK IN BACKGROUND THREAD
    Private Sub BackgroundWorker1_DoWork(sender As Object, e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker1.DoWork
        For i = 0 To 100
            If BackgroundWorker1.CancellationPending = True Then
                e.Cancel = True
                Exit For
            Else
                'DO HEAVY WORK
                DoHeavyWork()
                BackgroundWorker1.ReportProgress(i)

            End If
        Next
    End Sub

    'UPDATE PROGRESSBAR OR ANY UI COMPONENT
    Private Sub BackgroundWorker1_ProgressChanged(sender As Object, e As System.ComponentModel.ProgressChangedEventArgs) Handles BackgroundWorker1.ProgressChanged
        ProgressBar1.Value = e.ProgressPercentage
        Label1.Text = e.ProgressPercentage.ToString() + " %"
    End Sub

    'CALLED WHEN WORK IS OVER
    Private Sub BackgroundWorker1_RunWorkerCompleted(sender As Object, e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles BackgroundWorker1.RunWorkerCompleted
        'CHECKED IF CANCELLED,ERROR OR FINISHED
        If e.Cancelled = True Then
            MessageBox.Show("cancelled")
            ProgressBar1.Value = 0
            Label1.Text = ""
        ElseIf e.Error IsNot Nothing Then
            MessageBox.Show(e.Error.Message)
        Else
            MessageBox.Show("finished")
        End If
    End Sub

    Private Sub startBtn_Click(sender As Object, e As EventArgs) Handles startBtn.Click
        If Not BackgroundWorker1.IsBusy = True Then
            BackgroundWorker1.RunWorkerAsync()
        End If

    End Sub

    Private Sub cancelBtn_Click(sender As Object, e As EventArgs) Handles cancelBtn.Click
        If BackgroundWorker1.WorkerSupportsCancellation = True Then
            BackgroundWorker1.CancelAsync()
        End If
    End Sub
    Private Sub DoHeavyWork()
        System.Threading.Thread.Sleep(100)
    End Sub

End Class

Best Regards.

Comments