Reporting on Thread Progress
You may want to keep track of the background thread’s progress to keep an eye on things. This is also accomplished with a delegate and a property. The property is WorkerReportsProgress and the delegate is ProgressChanged. Listing 4 shows the property, the delegate, and the implementation of the ProgressChanged event handler.
Listing 4 Reporting on the background thread’s progress.
Imports System.ComponentModel Module Startup Sub Main() Dim worker As BackgroundWorker = New BackgroundWorker() AddHandler worker.DoWork, New DoWorkEventHandler(AddressOf OnWork) worker.WorkerReportsProgress = True AddHandler worker.ProgressChanged, _ New ProgressChangedEventHandler(AddressOf ProgressChanged) worker.RunWorkerAsync() Console.WriteLine("My thread is: " & _ System.Threading.Thread.CurrentThread.ManagedThreadId) Console.WriteLine("press enter") Console.ReadLine() End Sub Public Sub ProgressChanged(ByVal sender As Object, _ ByVal e As ProgressChangedEventArgs) Console.WriteLine("Percent complete: " & e.ProgressPercentage) End Sub Public Sub OnWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Console.WriteLine("Background thread is: " & _ System.Threading.Thread.CurrentThread.ManagedThreadId) Dim I As Integer For I = 1 To 100 CType(sender, BackgroundWorker).ReportProgress(I) System.Threading.Thread.Sleep(100) Next End Sub End Module
This example is arbitrarily contrived to make it easy to figure out the percentage complete; the example simply counts from 1 to 100. In a real-world situation, you’ll have to determine how to figure out how much work is yet to go, or you could simply loop the progress bar to show that something is happening.