thread.sleep, thread.sleep in c#,thread.sleep in c# console application, thread.sleep in c# windows application, thread.sleep in c# not working

Why you should avoid Thread.Sleep


Thread.Sleep allows user to hold or suspend or block the current thread execution till a predefined time.

it is implemented in System.Threading.Thread.dll assembly.

It has two overload method

public static void Sleep (int millisecondsTimeout);
public static void Sleep (TimeSpan timeout);

C# Source code to demonstrate thread sleep

using System;
using System.Threading;

class Program
    static void Main()
        for (int i = 0; i < 5; i++)
            //Perform some action
            Thread.Sleep(2000);//It will wait here for 2 seconds

Why you should avoid Thread.Sleep

Thread.Sleep required hardcoded sleep time value, which is not a good idea at all. In multithread applications, handling a race condition using Thread.Sleep is very difficult and annoying with hardcoded sleep time.

For example:
Let’s say we have defined hardcoded sleep time of 2 seconds (i.e. 2000 Milli-seconds) and the program just took 1 second to perform some action, still the thread will block its operation for another 1 seconds. Which is unnecessarily increasing the execution time.
Also, in some cases, as we have hardcoded sleeps time of 2 seconds but the program took 3 seconds to perform some action, so there is no guarantee of execution with predefined time.

Also there is come cost associate with it, as suspending or blocking the thread for some time and again re-awaken the thread exactly after hardcoded time, the program needs to consume some memory on the stack, it will also consuming/block resources of a machine

if we use Thread.Sleep with foreground thread then it will block Graphical User interface (GUI) for users i.e. user cannot click or perform any action on Graphical user interface (GUI) or even cannot terminate the Graphical User interface (GUI). If the thread is Background thread and let’s say its waiting in it and someone has closed the application, then the background thread will never be awoken

Avoid Thread.Sleep in Scenarios

Specifically, in the below scenarios, we should avoid the Thread.Sleep:

  • In thread synchronization and handling race conditions
  • Avoid using in foreground thread (GUI)
  • When start time and end times are not guaranteed

When to use Thread.Sleep

Below are some scenerios where we can consider Thread.Sleep

  • When we need periodic update or notification after some specific time interval
  • When we need to add a delay in the background thread.

Leave a Reply

Your email address will not be published. Required fields are marked *