2006-10-07
| Table of Contents: |
| Rate This Article: | Add This Article To: |
( Page 3 of 3 )
-On Demo"> A
BackgroundWorker Demo
Now let's take a look at a program that demonstrates the use of the
BackgroundWorker class and also shows how using multithreading can greatly
improve the responsiveness of the user interface. The program's one form is shown in the figure.
The form has two buttons to start the task, with or without creating a new thread for the task. When the task is running on a new thread, the Cancel button lets you cancel it. Below the Cancel button is a Progressbar that shows task progress (but only when the task is on its own thread).
The next element is a text box that you can try to edit while the task is running. You'll see that when the task is running without a new thread — in other words, using the program's one default thread — you will not be able to edit the text while the task is running, demonstrating how a long process can "freeze" the user interface. When the task is running on its own BackgroundWorker thread, however, you can edit without any problems; the user interface remains responsive.
The task in this case is a series of loops that takes about 10 seconds to complete. For execution without a new thread the program uses this method. If you want the task to take a longer or shorter time, change the value of the j or k loop.
Function ComputeWithoutThread() As String
Dim i As Integer
Dim j As Long
Dim k As Long
Dim q As Double
For i = 1 To 99
For j = 1 To 10000
For k = 1 To 1000
q = 1.56 ^ 0.43
Next k
Next j
Next i
Return "Task Completed"
End Function
To perform the same task on a new thread, the same loop code is embedded in a function that also includes progress updating and cancellation capabilities. Again, change the j or k loop to modify the duration of the task.
Function ComputeWithThread(ByVal worker As BackgroundWorker, _
ByVal e As DoWorkEventArgs) As String
Dim i As Integer
Dim j As Long
Dim k As Long
Dim q As Double
For i = 1 To 99
' Check for cancellation.
If worker.CancellationPending Then
e.Cancel = True
End
If
' Update the progress indicator.
worker.ReportProgress(i)
For j = 1 To 10000
For k = 1 To 1000
q = 1.56 ^ 0.43
Next k
Next j
Next i
Return "Task Completed"
End Function
Summing Up
Using multiple threads in your programs can be an essential programming technique for many kinds of applications. Whether you simply want to keep your UI responsive at all times, or whether you want to take advantage of the power of modern dual-core processors, multithreading can give your apps that extra edge that set them apart from the competition.
![]() |
|


