Thread.Sleep(2500) vs. Task.Delay(2500).Wait()

二次信任 提交于 2019-12-19 02:39:21

问题


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 block?

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().


回答1:


Using Wait on an uncompleted task is indeed blocking the thread until the task completes.

Using Thread.Sleep is clearer since you're explicitly blocking a thread instead of implicitly blocking on a task.

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.




回答2:


Thread.Sleep(...) creates an event to wake you up in X millisec, then puts your Thread to sleep... in X millisec, the event wakes you up.

Task.Delay(...).Wait() creates an event to start a Task in X millisec, then puts your Thread to sleep until the Task is done (with Wait)... in X millisec, the event starts the Task which ends immediately and then wakes you up.

Basically, they are both very similar. The only difference is if you want to wake up early from another Thread, you won't hit the same method.



来源:https://stackoverflow.com/questions/34052381/thread-sleep2500-vs-task-delay2500-wait

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!