Task.Delay
is implemented as follows:
public static Task Delay(int millisecondsDelay, CancellationToken cancellationToken)
{
//error checking
Task.DelayPromise delayPromise = new Task.DelayPromise(cancellationToken);
if (cancellationToken.CanBeCanceled)
delayPromise.Registration = cancellationToken.InternalRegisterWithoutEC((Action<object>) (state => ((Task.DelayPromise) state).Complete()), (object) delayPromise);
if (millisecondsDelay != -1)
{
delayPromise.Timer = new Timer((TimerCallback) (state => ((Task.DelayPromise) state).Complete()), (object) delayPromise, millisecondsDelay, -1);
delayPromise.Timer.KeepRootedWhileScheduled();
}
return (Task) delayPromise;
}
It definitely uses timers. They're used in a class called DelayPromise
. Here's the implementation for that:
private sealed class DelayPromise : Task<VoidTaskResult>
{
internal readonly CancellationToken Token;
internal CancellationTokenRegistration Registration;
internal Timer Timer;
internal DelayPromise(CancellationToken token)
{
this.Token = token;
}
internal void Complete()
{
if (!(this.Token.IsCancellationRequested ? this.TrySetCanceled(this.Token) : this.TrySetResult(new VoidTaskResult())))
return;
if (this.Timer != null)
this.Timer.Dispose();
this.Registration.Dispose();
}
}
It does use a timer, but it doesn't seem like a worry to me. The timer just calls back to the complete method, and what that does is check if it's canceled, if so cancel it, else just return a result. It seems fine to me.
Thread.Sleep
isn'tasync
?Task.Delay()
to appear to return immediately from the code that calls it, and the code following the delay will resume after the delay is over. It's non-blocking (as long as the method calling it is itselfasync
).Thread.Sleep
with argument other than 0 or 1 is always a big design problem.