task.wait,Task.delay和thread.sleep之间的差异

时间:2018-06-18 16:59:59

标签: c#-4.0 task-parallel-library

我想知道它们之间的区别 Task.delay Task.Wait和Thread.sleep

当我们使用thread.sleep时。从睡眠中醒来后,将创建一个新堆栈。请告诉我他们之间真正的区别。

1 个答案:

答案 0 :(得分:1)

基本上Wait()Sleep()都是线程阻塞操作,换句话说,它们强制线程处于空闲状态而不是在其他地方工作。另一方面,Delay在内部使用一个定时器来释放正在使用的线程,直到延迟完成。

关于这三个功能还有很多可以说的,所以这里有一个小样本集供进一步阅读。

更多信息

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