Sawyer
Sawyer

Reputation: 574

Should we use Task.Delay to replace Thread.Sleep

I am studying the new TPL to make my home made workflow work better.

Right now, I am entered into the maze of Task.Delay and Thread.Sleep. Acutally, Task.Delay(50).Wait() works just like Thread.Sleep(500). So which one should I use in my code?

from the many articles on internet, I have an impression that Task.Delay supports cancellation that Thread.Sleep does not support, so if I want to just block my thread for a duration without cancellation, will the use of Thread.Sleep be better than Task.Delay?

Upvotes: 1

Views: 343

Answers (2)

usr
usr

Reputation: 171188

If you require cancellation, Task.Delay is an easy solution to that. I has overhead on top of Thread.Sleep: It constructs a timer and when you wait on this task you construct a wait handle that is signaled by the timer.

That said, you will only notice this overhead in tight loops (and sleep-throttled loops are rarely tight).

Use Thread.Sleep for blocking without cancellation. This is how it has always been done. It is well-known and idiomatic. Use Task.Delay(...).Wait(); for cancellation support.

You can do this in many other ways. For example, construct a SemaphoreSlim or TaskCompletionSource and wait for it using a CancellationToken. That's not as simple as Task.Delay, though.

Upvotes: 5

ikh
ikh

Reputation: 10417

Maybe Thread.Sleep, which may call Sleep() API directly, will be better than Task.Delay, which create Task object. Task.Deley requires more overhead and a bit more long code.

the easier code is, the better.

Upvotes: 1

Related Questions