
You want to programmatically sleep or suspend a program using the VB.NET language. This can be accomplished with the Sleep (Thread.Sleep) method invocation; this method receives one parameter that indicates the number of milliseconds you want to pause the program.
This example program demonstrates how you can invoke the Sleep method on the Thread type. Please note how the Imports System.Threading line is included at the top of the program text; this enables the program to compile correctly. The Sleep(0) call pauses the program for zero milliseconds (no time); the Sleep(5000) call pauses for five seconds; the Sleep(1000) call pauses for one second. Also, the SpinWait method is used, and it results in a lot of CPU usage based on the large integer passed to it.
This VB example program shows the Sleep Function from System.Threading.
Program that demonstrates the Sleep method [VB.NET]
Imports System.Threading
Module Module1
Sub Main()
' Create a Stopwatch and sleep for zero milliseconds.
Dim stopwatch As Stopwatch = stopwatch.StartNew
Thread.Sleep(0)
stopwatch.Stop()
' Write the current time.
Console.WriteLine(stopwatch.ElapsedMilliseconds)
Console.WriteLine(DateTime.Now.ToLongTimeString)
' Start a new Stopwatch.
stopwatch = stopwatch.StartNew
Thread.Sleep(5000)
stopwatch.Stop()
Console.WriteLine(stopwatch.ElapsedMilliseconds)
Console.WriteLine(DateTime.Now.ToLongTimeString)
' Start a new Stopwatch.
stopwatch = stopwatch.StartNew
Thread.Sleep(1000)
stopwatch.Stop()
Console.WriteLine(stopwatch.ElapsedMilliseconds)
' Start a new Stopwatch and use SpinWait.
stopwatch = stopwatch.StartNew
Thread.SpinWait(1000000000)
stopwatch.Stop()
Console.WriteLine(stopwatch.ElapsedMilliseconds)
End Sub
End Module
Output
0
9:36:02 AM
4999
9:36:07 AM
999
3128
In this example, we tested the Thread.Sleep method in the VB.NET programming language. Again, to use the Thread.Sleep or Thread.SpinWait methods, please include the Imports System.Threading namespace. The Thread.Sleep method receives an integer indicating the number of milliseconds you want the program execution to pause; this results in 0% CPU usage. The Thread.SpinWait method receives an integer indicating the amount of work to do; this results in 100% CPU usage.
VB.NET Tutorials