本文介绍了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?
发布评论