Domanda

I found out that Thread.Sleep() is a lot useful when simulating long-lasting tasks and cancelling them in a graceful way (avoiding Thread.Abort()), On the other hand, I've read that using Thread.Sleep() for waiting other operations to end is a bad practice (we have Thread.Join() for doing it). I want to know if there's any application of Thread.Sleep() in a real production code/situation.

È stato utile?

Soluzione

Here are a few:

  1. Sleep(0) induces a context switch, yielding to another waiting thread of equal or higher priority.
  2. Sometimes, you don't want to use timers. Timer ticks can happen concurrently and timers cannot be stopped reliably. You can receive infinitely many ticks after a timer has been stopped due to race conditions (i.e. ticks might be queued and delivered later). If you want an action to performed one a minute, a sleep loop is a valid solution.
  3. Throttling of operations. Maybe you want to ask the Twitter only as much as you have quota.

Altri suggerimenti

Sure. If the spec says to wait 5 seconds, somewhere way down in a function somewhere, Sleep(5000) works for me, eg:

'After starting the compressor, wait five seconds for the pressure to stabilise before opening the fuel valve'.

The oft-derided Sleep() call does have some advantages. It involves no other threads to run timers. It works anywhere on any call stack of any depth on all threads. It does not require the rewriting of existing code as state-machines.

OTOH: It is often misused to poll inter-thread flags instead of using more appropriate and less wasteful inter-thread signaling. Sleep(0) and Sleep(1) loops are, more often than not, just a waste of time, CPU and memory-bandwidth.

It depends if you want or don't want to block the thread. Thread.Sleep() will block the thread.

It is useful if for example, you have a thread that sends request somewhere, but suddenly the connection drops, then you can use Thread.Sleep() to wait a little before trying again (it may be a transient connectivity error).

As I said, it will block the thread, so that thread gets frozen and nobody else can use it. Alternatively, you can use await Task.Delay() and release that thread to do something else till the given timeout expires.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top