task.wait,Task.delay和thread.sleep之间的区别 [英] Diference between task.wait , Task.delay and thread.sleep
问题描述
我想知道
Task.delay Task.Wait和Thread.sleep之间的区别
I would like to know the difference between Task.delay Task.Wait and Thread.sleep
当我们使用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.
推荐答案
基本上 Wait()
和 Sleep()
都是线程阻塞操作,换句话说,它们迫使线程处于空闲状态,而不是在其他地方工作。另一方面, Delay
在内部使用计时器,该计时器释放使用中的线程,直到完成延迟。
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.
更多信息
- There is no thread
- Don't Block on Async Code
- When to use Task.Delay, when to use Thread.Sleep?
- Thread.Sleep vs Task.Delay?
- Thread.Sleep is a sign of a poorly designed program.
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
}
}
这篇关于task.wait,Task.delay和thread.sleep之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!