Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any other use for Thread.Sleep() besides simulating long-lasting tasks?

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.

like image 507
Broken_Window Avatar asked Dec 28 '25 16:12

Broken_Window


1 Answers

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.
like image 72
usr Avatar answered Dec 31 '25 19:12

usr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!