Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread.Sleep vs Task.Delay?

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)

like image 474
Royi Namir Avatar asked Jun 23 '13 07:06

Royi Namir


People also ask

Is Task delay the same as thread sleep?

Thread. Sleep still ties up your Thread, Task. Delay release it to do other work while you wait.

Does task delay block thread?

Delay(1000) doesn't block the thread, unlike Task. Delay(1000).

What is Task delay in C#?

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.

Does task delay create a new thread?

Task. Delay does not create new Thread, but still may be heavy, and no guaranties on order of execution or being precise about deadlines.


1 Answers

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.

like image 161
Kevin Gosse Avatar answered Oct 15 '22 15:10

Kevin Gosse