Thread.sleep代码VS Task.Delay? [英] Thread.Sleep vs Task.Delay?
本文介绍了Thread.sleep代码VS Task.Delay?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我知道 Thread.sleep代码
块一个线程。
但是否 Task.Delay
也阻止?还是只是像定时器
,它使用一个线程用于所有的回调(当不重叠)?
But does Task.Delay
also block? Or is it just like Timer
which uses one thread for all callbacks (when not overlapping)?
(<一href="http://stackoverflow.com/questions/15341962/how-to-put-a-task-to-sleep-or-delay-in-c-sharp-4-0">this问题不包括差异)的
推荐答案
在MSDN上的文档是令人失望的,但反编译 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文