Thread.Sleep vs Task.Delay?

后端 未结 1 974
清酒与你
清酒与你 2020-12-03 00:18

I know that Thread.Sleep blocks a thread.

But does Task.Delay also block? Or is it just like Timer which uses one thread for

相关标签:
1条回答
  • 2020-12-03 00:56

    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.

    0 讨论(0)
提交回复
热议问题