C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Tip: You do not need to create a new Thread to use the Sleep method as it is static.
StaticHere: We call Sleep() 3 times. The surrounding code takes the system's time and uses Stopwatch to time the Thread.Sleep calls.
StopwatchC# program that sleeps
using System;
using System.Diagnostics;
using System.Threading;
class Program
{
static void Main()
{
//
// 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);
}
}
Output
0 ElapsedMilliseconds after Sleep(0)
8:14:43 AM Time after Sleep(0)
4999 ElapsedMilliseconds after Sleep(5000)
8:14:48 AM Time after Sleep(5000)
999 ElapsedMilliseconds after Sleep(1000)
3144 ElapsedMilliseconds after SpinWait(Int32)
Here: The program pauses for 3 seconds when it is executed, then prints a message to the console before it terminates.
C# program that uses TimeSpan overload
using System;
class Program
{
static void Main()
{
// Sleep for 3 seconds.
System.Threading.Thread.Sleep(TimeSpan.FromSeconds(3));
Console.WriteLine("[DONE]");
}
}
Output
[DONE]
So: You can insert a call to Sleep(), and then manually check the files (while Sleep is suspending the program's operation).
Tip: Thread.Sleep likely will end up calling the same code in the Windows kernel that the Sleep call in any language uses.
Important: The program only starts consuming the entire CPU core when the Thread.SpinWait method is invoked.
Info: Sleep uses the operating system to "pause" the program, resulting in 0% CPU, while Thread.SpinWait executes useless instructions.