1

I would like to know the difference between Task.delay Task.Wait and Thread.sleep

When we are using thread.sleep. After wake up from sleep a new stack is getting created. Please let me what is real difference between them.

Vipin
  • 938
  • 5
  • 18
  • 36
  • https://stackoverflow.com/a/20084603/5233410 – Nkosi Jun 18 '18 at 17:07
  • @Nkosi My question was on wait , delay and sleep. I think this link, they are talking only about delay and sleep. – Vipin Jun 18 '18 at 17:54
  • Does this answer your question? [When to use Task.Delay, when to use Thread.Sleep?](https://stackoverflow.com/questions/20082221/when-to-use-task-delay-when-to-use-thread-sleep) – T.Todua Jun 24 '22 at 15:47

1 Answers1

7

Basically Wait() and Sleep() are both thread blocking operations,in other words they force a thread to sit idle instead of doing work elsewhere. Delay on other hand uses a timer internally that releases the thread in use until the delay is complete.

There is much more that can be said about these three functions so here's a small sample set for further reading.

More Info


public class WaitSleepDelay
{
    /// <summary>
    /// The thread is released and is alerted when the delay finishes
    /// </summary>
    /// <returns></returns>
    public async Task Delay()
    {
        //This Code Executes
        await Task.Delay(1000); 
        //Now this code runs after 1000ms
    }

    /// <summary>
    /// This blocks the currently executing thread for the duration of the delay.
    /// This means that the thread is held hostage doing nothing 
    /// instead of being released to do more work.
    /// </summary>
    public void Sleep()
    {
        //This Code Executes
        Thread.Sleep(1000);
        //Now this code runs after 1000ms
    }

    /// <summary>
    /// This blocks the currently executing thread for the duration of the delay
    /// and will deadlock in single threaded sync context e.g. WPF, WinForms etc. 
    /// </summary>
    public void Wait()
    {
        //This Code Executes
        Task.Delay(1000).Wait();
        //This code may never execute during a deadlock
    }
}
JSteward
  • 6,833
  • 2
  • 21
  • 30