Starting the Thread
If this is your first multithreaded experience, there’s no need to get too fancy. For now, we’ll just indicate the thread ID of the thread executing and write that to the console. To start the background thread, we call RunWorkerAsync, as in worker.RunWorkerAsync (shown in bold in Listing 3).
Listing 3 Running the background thread.
Imports System.ComponentModel Module Startup Sub Main() Dim worker As BackgroundWorker = New BackgroundWorker() AddHandler worker.DoWork, New DoWorkEventHandler(AddressOf OnWork) worker.RunWorkerAsync() Console.WriteLine("My thread is: " & _ System.Threading.Thread.CurrentThread.ManagedThreadId) Console.WriteLine("press enter") Console.ReadLine() End Sub Public Sub OnWork(ByVal sender As Object, ByVal e As DoWorkEventArgs) Console.WriteLine("Background thread is: " & _ System.Threading.Thread.CurrentThread.ManagedThreadId) End Sub End Module
When you run the sample, the code in Main will likely finish before the identifier of the background thread is written to the console, even though the worker.RunWorkerAsync is called before the foreground thread is written to the console.