Vipin
Vipin

Reputation: 938

Diference between task.wait , Task.delay and thread.sleep

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.

Upvotes: 1

Views: 7001

Answers (1)

JSteward
JSteward

Reputation: 7091

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

Upvotes: 7

Related Questions