task.wait 、 Task.delay 和 thread.sleep 之间的区别

Vip*_*pin 1 task-parallel-library c#-4.0

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

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

JSt*_*ard 7

基本上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
    }
}
Run Code Online (Sandbox Code Playgroud)