Search code examples
c#.nettasktask-parallel-librarythread-sleep

Thread.Sleep() vs Task.Delay().Wait()


Codebase was like this in a non-async¹ method:

Thread.Sleep(500);

A colleague refactored it to be like this:

Task.Delay(500).Wait();

Given the relative small delay, is really an advantage to use the async version (Task.Delay()) ?
Does it change if the delay is a bunch of millisecond or a bunch of seconds ?
More important... Is not the .Wait() defeating he purpose of making an async ?

To provide more context, this is executes in a background process that runs an average of every minute.

Isn't this second approach just wasting more resources ? (as some comments here seems to indicate)

[Edit]
The await is not used in this case because the method is NOT async.
My colleague prefers Task.Delay(N).Wait() to Thread.Sleep(N).
Where the method is async he used await and not .Wait().

In this specific case the method is called when an API endpoint is hit and send a request to an external service and tries 3 or 5 times (with a delay) until it gets the result (kind of polling).

¹ Originally the method was mentioned to be async.


Solution

  • await Task.Delay(500);
    

    You should almost never use .Wait(), but Task.Delay(...).Wait() is a special circle of "nope".

    Thread.Sleep(...) is ok if you are happy with blocking the current thread; you shouldn't do that on a concurrent application (such as a server), though.


    yes, there are scenarios where it is acceptable or even necessary; but if you have to ask: "don't" is a good default answer; any full answer on this involves multiple pages of context, nuance, etc.