Home
VB.NET
Thread.Sleep Subroutine (Pause)
Updated Apr 14, 2023
Dot Net Perls
Sleep. This VB.NET Subroutine causes a program to suspend operation. It receives 1 integer parameter—the number of milliseconds to pause the program.
Integer
CPU notes. No CPU time is used by Sleep. The program simply ceases to operate. For CPU usage, consider SpinWait, which causes a delay by wasting processor cycles.
Sub
First example. Here we invoke the Sleep Sub on the Thread type. Please note how the Imports System.Threading line is included at the top of the program.
Info Sleep 0 pauses the program for zero milliseconds. Sleep 5000 pauses for five seconds. Sleep 1000 pauses for one second.
Here We invoke SpinWait(). This subroutine results in a lot of CPU usage based on the large integer passed to it.
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
0 9:36:02 AM 4999 9:36:07 AM 999 3128
Namespace. To use Thread.Sleep or Thread.SpinWait, import the System.Threading namespace. These methods are part of Threading, as they are more useful when threads are involved.
A summary. The Thread.Sleep method receives an integer indicating the number of milliseconds you want the program execution to pause.
Summary, continued. The Thread.SpinWait method receives an integer indicating the amount of work to do. This results in 100% CPU usage.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Apr 14, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen