In C#, a Sleep() method temporarily suspends the current execution of the thread for specified milliseconds, so that other threads can get the chance to start the execution, or may get the CPU for execution. There are two methods in the overload list of Thread.Sleep
Method as follows:
- Sleep(Int32)
- Sleep(TimeSpan)
Sleep(Int32)
This method suspends the current thread for the descriptor number of milliseconds. This method will throw an ArgumentOutOfRangeException if the time-out value is negative and is not equal to infinite.
Syntax:
public static void Sleep (int millisecondsTimeout);
Here, millisecondsTimeout is a number of milliseconds for which the thread is suspended. If the value of the millisecondsTimeout argument is zero, then the thread renounces the remainder of its time slice to any thread of equal priority that is ready to run. If there are no other threads of equal priority that are ready to run, then execution of the current thread is not suspended.
Example:
using System;
using System.Threading;
class ExampleofThread {
public void thread1()
{
for ( int x = 0; x < 2; x++) {
Console.WriteLine( "Thread1 is working" );
Thread.Sleep(4000);
}
}
public void thread2()
{
for ( int x = 0; x < 2; x++) {
Console.WriteLine( "Thread2 is working" );
}
}
}
public class ThreadExample {
public static void Main()
{
ExampleofThread obj = new ExampleofThread();
Thread thr1 = new Thread( new ThreadStart(obj.thread1));
Thread thr2 = new Thread( new ThreadStart(obj.thread2));
thr1.Start();
thr2.Start();
}
}
|
Output:
Thread1 is working
Thread2 is working
Thread2 is working
Thread1 is working
Explanation: By using Thread.Sleep(4000);
in the thread1 method, we make the thr1 thread sleep for 4 seconds, so in between 4 seconds the thr2 thread gets the chance to execute after 4 seconds the thr1 thread resume its working.
Sleep(TimeSpan)
This method suspends the current thread for the described amount of time. This method will throw an ArgumentOutOfRangeException if the value of timeout is negative and is not equal to the infinite in milliseconds, or is greater than MaxValue milliseconds.
Syntax :
public static void Sleep (TimeSpan timeout);
Here, the timeout is the amount of time for which the thread is suspended. If the value of the millisecondsTimeout argument is Zero, then the thread renounces the remainder of its time slice to any thread of equal priority that is ready to run. If there are no other threads of equal priority that are ready to run, then execution of the current thread is not suspended.
Example:
using System;
using System.Threading;
class GFG {
static void Main()
{
TimeSpan timeout = new TimeSpan(0, 0, 3);
for ( int k = 0; k < 3; k++) {
Console.WriteLine( "Thread is" +
" sleeping for 3 seconds." );
Thread.Sleep(timeout);
}
Console.WriteLine( "Main thread exits" );
}
}
|
Output:
Thread is sleeping for 3 seconds.
Thread is sleeping for 3 seconds.
Thread is sleeping for 3 seconds.
Main thread exits
Reference: