Blog

How to pause a thread in VB.NET

Posted by Rohatash Kumar Blogs | Multithreading in VB.NET Jul 27, 2011
This blog defines how to start and pause a thread in VB.NET.

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.

post comment
     
COMMENT USING
PREMIUM SPONSORS
Over-C is a holistic consortium of communications and technology specialists. We build, deploy and market both business as well as consumer products and solutions.
Get Career Advice from Experts
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter