Thread.Sleep(2500)与Task.Delay(2500).Wait() [英] Thread.Sleep(2500) vs. Task.Delay(2500).Wait()

查看:155
本文介绍了Thread.Sleep(2500)与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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆