Namespace

In .NET, threading functionality is defined in System.Threading namespace. So you have to define System.Threading namespace before using any thread classes.

Imports System.Threading

Starting a Thread

A Visual Basic client program starts in a single thread created automatically by the CLR and operating system that is called main thread, and is made multithreaded by creating additional threads. Here's a simple example and its output.

Imports System.Threading

Module Module1

Sub Main()

Dim th As New Thread(AddressOf WriteY)

th.Start()

For i As Integer = 0 To 10

Console.WriteLine("Hello")

Next

End Sub

Private Sub WriteY()

For i As Integer = 0 To 9

Console.Write("world")

Next

End Sub

End Module

In the above example, The main thread creates a new thread th on which it runs a method that repeatedly prints the string “world”. Simultaneously, the main thread repeatedly prints the string“Hello”.

Pausing a Thread

Thread.Sleep method can be used to pause a thread for a fixed period of time.

thread.Sleep()

Here's a simple example and its output.

Imports System.Threading

Module Module1

Sub Main()

Dim th As New Thread(AddressOf WriteY)

th.Start()

For i As Integer = 0 To 10

Console.WriteLine("Hello")

Thread.Sleep(1000)

Next

End Sub

Private Sub WriteY()

For i As Integer = 0 To 9

Console.WriteLine("world")

Thread.Sleep(500)

Next

End Sub

End Module

In the above example, The main thread creates a new thread th which is pause by sleep method for 500 milliseconds. The main thread is also pause by sleep method for 1000 milliseconds.