Let's switch to the code behind of the Windows form and do the coding. First, import the following namespace:

Imports System.ComponentModel

When the Start button is clicked, you first initialize some of the controls
on the form. You also change the cursor to an hourglass (Cursors.WaitCursor)
so that the user knows the application is working. You then get the BackgroundWorker
component to spin off a separate thread using the RunWorkAsync()
method. You pass the number entered by the user as the parameter for this method:

The DoWork event of the BackgroundWorker component will invoke
the SumNumbers() function (which I will define next) in a separate
thread. This event (DoWork) is fired when you call the RunWorkerAsync()
method (as was done in the previous step).

The SumNumbers() function basically sums up all the numbers from
0 to the number specified. It takes in three arguments--the number to sum up
to, the BackgroundWorker, and the DoWorkEventArgs. Note that within
the For loop, you check to see if the user has clicked on the Cancel
button (the event will be defined later in this article) by checking the value
of the CancellationPending property. If the user has cancelled
the process, set e.Cancel to True. For every ten iterations,
I will also calculate the progress completed so far. If there is progress (when
the current progress percentage is greater than the last one recorded), then
I will update the progress bar by calling the ReportProgress()
method of the BackgroundWorker component. You should not call the ReportProgress()
method unnecessarily, as frequent calls to update the progress bar will freeze
the UI of your application.

It is important that note that in this method (which was invoked by the DoWork
event), you cannot directly access the Windows controls, as they are not thread-safe. Trying to do so will also trigger a runtime error, a useful feature new
in Visual Studio 2005.

Function SumNumbers( _
ByVal number As Double, _
ByVal worker As System.ComponentModel.BackgroundWorker, _
ByVal e As DoWorkEventArgs) As Double
Dim lastPercent As Integer = 0
Dim sum As Double = 0
For i As Double = 0 To number
'---check if user cancelled the process
If worker.CancellationPending = True Then
e.Cancel = True
Else
sum += i
If i Mod 10 = 0 Then
Dim percentDone As Integer = i / number * 100
'---update the progress bar if there is a change
If percentDone > lastPercent Then
worker.ReportProgress(percentDone)
lastPercent = percentDone
End If
End If
End If
Next
Return sum
End Function

The ProgressChanged event is invoked whenever the ReportProgress()
method is called. In this case, I used it to update my progress bar:

Testing the Application

To test the application, press F5 and enter a large number (say, 9999999)
and click the Start button. You should see the progress bar updating and the
cursor changed to an hourglass. When the process is completed, the result will
be printed in the Label control (see Figure 4).