This question already has an answer here:
- When to use Task.Delay, when to use Thread.Sleep? 4 answers
I have recently seen several recommendations stating that Thread.Sleep
should never be used in production code (most recently in this SO question). Many of these advocate for using Task.Delay
instead. Most of the explanations I've found use UI applications as examples, since the advantages to Task.Delay
are obvious (not blocking the UI).
In my case, I am using Thread.Sleep
inside of a wait loop that polls a WCF service for a particular condition, like this:
DateTime end = DateTime.UtcNow + TimeSpan.FromMinutes(2);
while (DateTime.UtcNow < end)
{
if (ExternalServiceIsReady() == true)
{
return true;
}
Thread.Sleep(1000);
}
In this case, the following potential advantages of Task.Delay
seem not to apply:
- The sleep time is fairly large relative to the typical timer resolution of around 15 ms, so the increase in accuracy of
Task.Delay
seems trivial. - The process is single-threaded (non-UI) and must block until the condition is true, so using
await
has no advantage here. - The ability to cancel the delay is not required.
Is this a case where it is appropriate to use Thread.Sleep
? What would be the advantage (if any) of replacing my sleep line with Task.Delay(1000).Wait()
?