Thread.Sleep a method used to suspend current thread for a specific interval of time. Time can be specified in milliseconds.
While in a Sleep mode a method does not consumes any CPU resources so indirectly it save memory for other thread processes.
On the same we will create a simple example where in the for loop while printing output we will make a thread to sleep for 1000 milliseconds i.e. 1 sec for per print.
C# Thread program example using Sleep method
Code
using System;
using System.Threading;
using System.Threading.Tasks;
class Program
{
static void Main(string[] args)
{
Thread t1 = new Thread(PrintEven);
Thread t2 = new Thread(PrintOdd);
t1.Start();
t2.Start();
t2.Join();
}
static void PrintEven()
{
for (int i = 0; i <= 10; i=i+2)
{
Console.WriteLine(i);
Thread.Sleep(1000);
}
}
static void PrintOdd()
{
for (int i = 1; i <= 10; i = i + 2)
{
Console.WriteLine(i);
Thread.Sleep(1000);
}
}
}
As you see from above example we have implemented Sleep method in a PrintEven and PrintOdd methods and made thread to sleep for 1 sec for each print.
Output:
Main thread started
Printing the Number sequence 1 to 10
0
1
2
3
4
5
6
7
8
9
10
Main Thread Ended
If we observe the above output in the console of c# application, it will take one sec gap for printing digit after digit.