Thread.Sleep(2500) vs. Task.Delay(2500).Wait()
Solution 1
Using Wait
on an uncompleted task is indeed blocking the thread until the task completes.
Using Thread.Sleep
is clearer since you're explicitly blocking a thread instead of implicitly blocking on a task.
The only way using Task.Delay
is preferable is that it allows using a CancellationToken
so you can cancel the block if you like to.
Solution 2
Thread.Sleep(...)
creates an event to wake you up in X millisec, then puts your Thread to sleep... in X millisec, the event wakes you up.
Task.Delay(...).Wait()
creates an event to start a Task in X millisec, then puts your Thread to sleep until the Task is done (with Wait)... in X millisec, the event starts the Task which ends immediately and then wakes you up.
Basically, they are both very similar. The only difference is if you want to wake up early from another Thread, you won't hit the same method.
David Pine
[![Microsoft - MVP][1]][1] Follow me on Twitter @davidpine7 https://davidpine.net/ https://ievangelistblog.wordpress.com/
Updated on June 05, 2022Comments
-
David Pine over 1 year
I want some clarity on this. I know that
Task.Delay
will internally use a Timer and it is obviously task-based (awaitable), whereasThread.Sleep
will cause the thread to be blocked. However, does calling.Wait
on the task cause the thread to be blocked?If not, one would assume that
Task.Delay(2500).Wait()
is better thanThread.Sleep(2500)
. This is slightly different that the SO question/answer here as I'm calling.Wait()
. -
Bradley Uffner about 8 years...But only if you have another thread running that can use the
CancellationToken
as the main thread will be blocked. -
i3arnon about 8 years@BradleyUffner well, you can create a self cancelling token (using a timer internally)...
-
Voo about 8 years"Task.Delay(...).Wait() creates an event to start a Task in X millisec, then puts your Thread to sleep until the Task is done" There's no task being created here.
-
Guillaume F. about 8 yearsYes there is one, but it's empty. Delay returns a Task object.
-
Voo about 8 yearsYeah badly formulated. No task is ever started. There's just a task object which is created by the TaskCompletionSource and whose state is updated after a while.