C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
AddressOf: Please use the AddressOf operator and specify the method name as the first argument.
Tip: You can pass anything as the second argument. It will be cast to an Object, which you can then recast in the specified method.
Tip 2: Pay attention to how the WaitCallback is passed as an argument. This syntax is a bit confusing.
Info: This program creates a new thread in the thread pool and executes the code. It passes an argument from the main thread to the sub-thread method.
VB.NET program that uses ThreadPool.QueueUserWorkItem
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 Module
Output
4
And: The second is an Object that is used by the Monitor.Enter and Monitor.Exit subroutines.
IntegerFirst: A loop creates ten threaded calls to the subroutine Process. In Process we recast the argument and then invoke Monitor.Enter and Monitor.Exit.
Tip: The monitor calls ensure that no two threads will mutate the Integer at once.
Important: This example demonstrates the use of QueueUserWorkItem and it further shows the Monitor.Enter and Monitor.Exit methods.
VB.NET program that uses loop with QueueUserWorkItem
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 Module
Output
55
Note: For threaded programs, I almost always reach for BackgroundWorker because it is very reliable and less confusing for novices.
BackgroundWorkerReview: ThreadPool reduces the amount of thread management logic you must create and test.