【发布时间】:2013-06-23 07:00:24
【问题描述】:
【问题讨论】:
-
这里有一个小 wiki 演示,其中突出显示了两者之间的一些阻塞差异。
标签: c# multithreading .net-4.0 .net-4.5
【问题讨论】:
标签: c# multithreading .net-4.0 .net-4.5
MSDN 上的文档令人失望,但使用 Reflector 反编译 Task.Delay 会提供更多信息:
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;
}
基本上,这个方法只是一个包裹在任务中的计时器。所以是的,你可以说它就像计时器。
【讨论】: