Thread.Sleep() против Task.Delay().Wait()C#

Место общения программистов C#
Гость
Thread.Sleep() против Task.Delay().Wait()

Сообщение Гость »


Кодовая база была такой в ​​каком-то асинхронном методе:

(см. «Редактирование», этот конкретный случай НЕ был асинхронным)

Код: Выделить всё

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 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).


Источник: https://stackoverflow.com/questions/780 ... delay-wait

Вернуться в «C#»