Thread.Sleep vs Task.Delay?

时间:2013-06-23 07:00:25

标签: c# multithreading .net-4.0 .net-4.5

我知道Thread.Sleep会阻塞一个帖子。

Task.Delay也阻止了吗?或者它就像Timer使用一个线程进行所有回调(当不重叠时)?

this问题未涵盖差异)

1 个答案:

答案 0 :(得分:52)

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;
}

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