Introduction
Threading is a fundamental concept for building responsive and high‑performance applications. This article covers advanced threading techniques in Visual Basic .NET, including the Thread
class, thread pools, synchronization primitives, and best practices.
Using the Thread
Class
The System.Threading.Thread
class provides low‑level control over a thread's lifecycle.
Imports System.Threading
Module ThreadDemo
Sub Main()
Dim t As New Thread(AddressOf Worker)
t.Name = "WorkerThread"
t.IsBackground = True
t.Start()
Console.WriteLine("Main thread continues...")
End Sub
Private Sub Worker()
For i As Integer = 1 To 5
Thread.Sleep(500)
Console.WriteLine($"Worker iteration {i}")
Next
End Sub
End Module
Thread Pool
For short‑lived operations, the thread pool reduces overhead.
Imports System.Threading
Module ThreadPoolDemo
Sub Main()
For i As Integer = 1 To 3
ThreadPool.QueueUserWorkItem(AddressOf DoWork, i)
Next
Console.ReadLine()
End Sub
Private Sub DoWork(state As Object)
Dim id = DirectCast(state, Integer)
Console.WriteLine($"Task {id} starting on thread {Thread.CurrentThread.ManagedThreadId}")
Thread.Sleep(1000)
Console.WriteLine($"Task {id} completed")
End Sub
End Module
Synchronization Primitives
Protect shared resources using Monitor
, Mutex
, SemaphoreSlim
, or ReaderWriterLockSlim
.
Imports System.Threading
Module SyncDemo
Private counter As Integer = 0
Private lockObj As New Object()
Sub Main()
For i As Integer = 1 To 5
Dim t As New Thread(AddressOf Increment)
t.Start()
Next
Thread.Sleep(2000)
Console.WriteLine($"Final counter value: {counter}")
End Sub
Private Sub Increment()
SyncLock lockObj
Dim temp = counter
Thread.Sleep(100) ' Simulate work
counter = temp + 1
End SyncLock
End Sub
End Module
Best Practices
- Prefer the Task Parallel Library (TPL) over raw
Thread
objects. - Avoid blocking calls on the UI thread; use
await
or background workers. - Use
CancellationToken
to support cooperative cancellation. - Limit the degree of parallelism for CPU‑bound work.
- Never lock on publicly accessible objects.