This C# method pauses programs. It receives a value indicating the number of milliseconds to wait. It sometimes helps with diagnosing a problem.
Calling Sleep can be useful for waiting on an external application or task. It does not cause CPU usage during the pause. SpinWait
, meanwhile, does cause CPU usage.
Sleep is found on the Thread class
. It is a static
method that receives one parameter. You must either include System.Threading
or call System.Threading.Thread.Sleep
.
static
.Sleep()
3 times. The surrounding code takes the system's time and uses Stopwatch
to time the Thread.Sleep
calls.using System; using System.Diagnostics; using System.Threading; // // Demonstrates 3 different ways of calling Sleep. // var stopwatch = Stopwatch.StartNew(); Thread.Sleep(0); stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedMilliseconds); Console.WriteLine(DateTime.Now.ToLongTimeString()); stopwatch = Stopwatch.StartNew(); Thread.Sleep(5000); stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedMilliseconds); Console.WriteLine(DateTime.Now.ToLongTimeString()); stopwatch = Stopwatch.StartNew(); System.Threading.Thread.Sleep(1000); stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedMilliseconds); // // Bonus: shows SpinWait method. // stopwatch = Stopwatch.StartNew(); Thread.SpinWait(100000 * 10000); stopwatch.Stop(); Console.WriteLine(stopwatch.ElapsedMilliseconds);0 3:29:29 PM 5005 3:29:34 PM 1005 356
TimeSpan
We can also use Sleep()
with a TimeSpan
argument. To sleep for 3 seconds, for example, we can pass in a TimeSpan
created with the TimeSpan.FromSeconds
method.
using System; // Sleep for 3 seconds. System.Threading.Thread.Sleep(TimeSpan.FromSeconds(3)); Console.WriteLine("[DONE]");[DONE]
Suppose you have a program that modifies external files. You want to see how the files have been modified at a certain point.
Sleep()
, and then manually check the files (while Sleep is suspending the program's operation).SpinWait
When you execute the first program, you will notice that the program does not require significant CPU time when executing the Thread.Sleep
calls.
Thread.SpinWait
method is invoked.Thread.SpinWait
executes useless instructions.Thread.Sleep
is fairly accurate in pausing the program for the specified number of milliseconds. Unlike SpinWait
, Sleep does not cause your program to consume 100% CPU.