Thread.Sleep(2500)与Task.Delay(2500).Wait() [英] Thread.Sleep(2500) vs. Task.Delay(2500).Wait()
问题描述
我希望对此有所澄清.我知道Task.Delay
将在内部使用一个Timer,它显然是基于任务的(可等待的),而Thread.Sleep
则会导致线程被阻塞.但是,在任务上调用.Wait
是否会导致线程被阻塞?
I want some clarity on this. I know that Task.Delay
will internally use a Timer and it is obviously task-based (awaitable), whereas Thread.Sleep
will cause the thread to be blocked. However, does calling .Wait
on the task cause the thread to be blocked?
如果没有,人们会认为Task.Delay(2500).Wait()
比Thread.Sleep(2500)
好.这与在此处提出问题/答案,因为我正在呼叫.Wait()
.
If not, one would assume that Task.Delay(2500).Wait()
is better than Thread.Sleep(2500)
. This is slightly different that the SO question/answer here as I'm calling .Wait()
.
推荐答案
在未完成的任务上使用Wait
确实会阻塞线程,直到任务完成.
Using Wait
on an uncompleted task is indeed blocking the thread until the task completes.
使用Thread.Sleep
更加清晰,因为您显式地阻塞了线程,而不是隐式地阻塞了任务.
Using Thread.Sleep
is clearer since you're explicitly blocking a thread instead of implicitly blocking on a task.
首选使用Task.Delay
的唯一方法是它允许使用CancellationToken
,因此您可以根据需要取消该块.
The only way using Task.Delay
is preferable is that it allows using a CancellationToken
so you can cancel the block if you like to.
这篇关于Thread.Sleep(2500)与Task.Delay(2500).Wait()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!