Thread.Sleep vs Task.Delay?

编程入门 行业动态 更新时间:2024-10-25 08:27:22
本文介绍了Thread.Sleep vs Task.Delay?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道 Thread.Sleep 阻塞了一个线程.

I know that Thread.Sleep blocks a thread.

但是Task.Delay 也会阻塞吗?还是就像 Timer 一样,所有回调都使用一个线程(不重叠时)?

But does Task.Delay also block? Or is it just like Timer which uses one thread for all callbacks (when not overlapping)?

(这个问题没有涵盖差异)

推荐答案

MSDN 上的文档令人失望,但使用 Reflector 反编译 Task.Delay 提供了更多信息:

The documentation on MSDN is disappointing, but decompiling Task.Delay using Reflector gives more information:

public static Task Delay(int millisecondsDelay, CancellationToken cancellationToken) { if (millisecondsDelay < -1) { throw new ArgumentOutOfRangeException("millisecondsDelay", Environment.GetResourceString("Task_Delay_InvalidMillisecondsDelay")); } if (cancellationToken.IsCancellationRequested) { return FromCancellation(cancellationToken); } if (millisecondsDelay == 0) { return CompletedTask; } DelayPromise state = new DelayPromise(cancellationToken); if (cancellationToken.CanBeCanceled) { state.Registration = cancellationToken.InternalRegisterWithoutEC(delegate (object state) { ((DelayPromise) state).Complete(); }, state); } if (millisecondsDelay != -1) { state.Timer = new Timer(delegate (object state) { ((DelayPromise) state).Complete(); }, state, millisecondsDelay, -1); state.Timer.KeepRootedWhileScheduled(); } return state; }

基本上,这个方法只是一个包裹在任务中的定时器.所以是的,你可以说它就像计时器.

Basically, this method is just a timer wrapped inside of a task. So yes, you can say it's just like timer.

更多推荐

Thread.Sleep vs Task.Delay?

本文发布于:2023-11-08 16:17:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569861.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Sleep   Thread   Delay   Task

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!