In learning .NET 4.5, I get the impression that System.Threading.Tasks.Task.Delay(1000).Wait()
(i.e. the blocking delay) is preferred over System.Threading.Thread.Sleep(1000)
. Is that true, and, if so, why? Is it simply because the .NET marching orders have always been "use the latest technology whenever possible"?
Asked
Active
Viewed 749 times
3

rory.ap
- 34,009
- 10
- 83
- 174
-
Are you sure the first part is `Task.Delay().Wait()`? This will block the thread in the same way that `Sleep` does, only in a more expensive way. Perhaps it was `await Task.Delay()`? – Panagiotis Kanavos Dec 19 '14 at 14:48
-
@PanagiotisKanavos -- Yes, my question is specifically about the blocking kind of delay (like `Sleep`) where blocking is preferred. Your allusion to it being more "expensive" is the kind of answer I'm looking for. – rory.ap Dec 19 '14 at 14:49
-
1No, you misunderstood. They are just as bad as they do the same bad thing, only Task.Delay.Wait goes through the threadpool to unfreeze the thread. Actually, that T.D.W. evokes a W.T.F. reaction in me. No official or semi-official blog advocates using this construct. – Panagiotis Kanavos Dec 19 '14 at 15:12
-
@PanagiotisKanavos -- Yeah, I saw it used in the answer [here](http://stackoverflow.com/questions/13806153/example-of-named-pipes), which is why I was curious. – rory.ap Dec 19 '14 at 15:28
-
That doesn't mean it's a recommendation. Just that the answerer wanted to add a delay and typed whatever came to mind. You can't execute asynchronously the main method of a console application so any Tasks used there have to be explicitly awaited with a `.Wait()` call – Panagiotis Kanavos Dec 19 '14 at 15:31
1 Answers
3
Thread.Sleep(1000)
is preferred because it is the idiomatic way to perform a synchronous wait. It has been the standard for 15 years now. There is nothing wrong with it.
Task.Delay(1000).Wait()
does the same thing. It is harder to understand, slower to type, slower to execute and, in my mind, backwards thinking.
If you want a synchronous operation call the synchronous API made for that. Sleeping is not special in this regard.

usr
- 168,620
- 35
- 240
- 369