ThreadPool
The VB.NET ThreadPool
type allows us to create and handle many threads. We optimize when they run for the best performance.
With ThreadPool
, we account for multiple cores and processors. ThreadPool
eliminates our need to implement complicated logic that allocates threads.
We use QueueUserWorkItem
. This function receives two parameters: a WaitCallback
instance, which is assigned to a subroutine address, and an argument of type Object.
AddressOf
operator and specify the method name as the first argument.WaitCallback
is passed as an argument. This syntax is a bit confusing.ThreadPool
and executes the code. It passes an argument to the threaded method.Imports System.Threading Module Module1 Sub Main() ' Use this argument to the thread. Dim t As String = "test" ThreadPool.QueueUserWorkItem(New WaitCallback(AddressOf Process), t) ' Wait a while. Thread.Sleep(50) End Sub Sub Process(ByVal arg As Object) ' Cast the argument and display its length. Dim t As String = arg Console.WriteLine(t.Length) End Sub End Module4
This ThreadPool
example builds on our understanding of the thread pool. Two fields are used—an Integer is accessed by the threaded methods.
Monitor.Enter
and Monitor.Exit
subroutines.Monitor.Enter
and Monitor.Exit
.QueueUserWorkItem
and it further shows the Monitor.Enter
and Monitor.Exit
methods.Imports System.Threading Module Module1 Private _int As Integer Private _obj As Object = New Object Sub Main() ' WaitCallback instance. Dim w As WaitCallback = New WaitCallback(AddressOf Process) ' Loop over these values. For var As Integer = 0 To 10 ThreadPool.QueueUserWorkItem(w, var) Next ' Wait a while. Thread.Sleep(50) ' Write integer. Console.WriteLine(_int) End Sub Sub Process(ByVal arg As Object) ' Cast the argument and display it. Dim t As Integer = arg ' Lock the integer. Monitor.Enter(_obj) ' Change value. _int += t ' Unlock. Monitor.Exit(_obj) End Sub End Module55
The example program prints 55, the sum of all numbers in the range of 0 to 10. It did this by using 10 threaded method calls.
ThreadPool
, these could be run on any number of processors. For a more complex calculation, this could be useful.BackgroundWorker
Often we prefer the BackgroundWorker
type over the ThreadPool
type. The BackgroundWorker
seems easier to use and overall more intuitive.
BackgroundWorker
because it is very reliable and less confusing for novices.As part of the System.Threading
namespace, the ThreadPool
type provides multiple threads support in the VB.NET language. ThreadPool
simplifies thread management logic.