什么时候用Task.Delay,什么时候用Thread.Sleep? [英] When to use Task.Delay, when to use Thread.Sleep?
本文介绍了什么时候用Task.Delay,什么时候用Thread.Sleep?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有关于何时使用 Task.Delay 与 Thread.Sleep?
Are there good rule(s) for when to use Task.Delay versus Thread.Sleep?
- 具体来说,是否有一个最小值可以让一个比另一个更有效/高效?
- 最后,由于 Task.Delay 导致 async/await 状态机上的上下文切换,使用它是否有开销?
推荐答案
使用 Thread.Sleep
当你想阻塞当前线程时.
Use Thread.Sleep
when you want to block the current thread.
使用Task.Delay
当你想要一个逻辑延迟而不阻塞当前线程时.
Use Task.Delay
when you want a logical delay without blocking the current thread.
效率不应成为这些方法的首要考虑.它们在现实世界中的主要用途是作为 I/O 操作的重试计时器,其数量级为秒而不是毫秒.
Efficiency should not be a paramount concern with these methods. Their primary real-world use is as retry timers for I/O operations, which are on the order of seconds rather than milliseconds.
这篇关于什么时候用Task.Delay,什么时候用Thread.Sleep?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文