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:
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: