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 all callbacks (when not overlapping)?
(this question doesn't cover the differences)
Thread. Sleep still ties up your Thread, Task. Delay release it to do other work while you wait.
Delay(1000) doesn't block the thread, unlike Task. Delay(1000).
Delay(TimeSpan) Creates a task that completes after a specified time interval. Delay(Int32, CancellationToken) Creates a cancellable task that completes after a specified number of milliseconds.
Task. Delay does not create new Thread, but still may be heavy, and no guaranties on order of execution or being precise about deadlines.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With