When is it sensible to use Thread.Sleep()?

15,404

Solution 1

You should call Thread.sleep() when you actually need a delay in a background thread.

Do not call it to help synchronization (it won't), don't call it in a loop to wait for something (it'll be slow) and never call it on a UI thread (it'll freeze).

Solution 2

There are very few situations where I'd consider it acceptable. Ultimately it comes down to the following conditions in my mind- others may chime in on cases where these don't apply, but as a rule of thumb ALL of the following would need to be true for me to use Thread.Sleep in production (aka not trivial or testing) code:

  1. You are waiting on a resource
  2. The resource in question does not provide proper proactive notification of readiness (a WaitHandle or something)
  3. You cannot otherwise modify the resource in question to do so
  4. You have measured and know that you need to wait long enough that a SpinWait is not justified, and that you get better performance by leaving the context.

Solution 3

When you need to introduce a pause in some throwaway or testing code, Thread.Sleep() is fine.

In production code, it's best to try to find a different option. For example, if you're trying to do something on an interval, use one of the many pre-existing timer classes. If you're trying to pause when an input queue empties (and on .NET), consider using Monitor.Wait() and Monitor.Pulse() instead.

More (again, .NET-centric) explanation of the downsides of Sleep() in this article: Thread.Sleep is a sign of a poorly designed program.

Solution 4

When writing test code. If you want to see how some a function handles being called by multiple threads at random.

Also, if you want to simulate a delay for testing. Say you wanted to test a progress bar.

Share:
15,404

Related videos on Youtube

ediblecode
Author by

ediblecode

Casual gamer, part-time genius and programmer working in London

Updated on February 24, 2020

Comments

  • ediblecode
    ediblecode over 4 years

    I always see people using Thread.Sleep() for creating delays in processing or something similar and people are always derided for using it this way.

    When is it sensible/required to use Thread.Sleep()?

    • ediblecode
      ediblecode over 12 years
      Why have people down voted this question without any explanation as to why?
    • Erick Robertson
      Erick Robertson over 12 years
      -1 Please pick one language. The answer to this question will reference other libraries. It's confusing to ask this question about two different languages at the same time.
    • ediblecode
      ediblecode over 12 years
      @ErickRobertson So are you saying that two questions should be created? Seems a bit inconsequential to me.
    • adelphus
      adelphus over 12 years
      It's amazing that so many people seem to think Sleep() == Bad Design. Like every other API, Sleep() is designed for a specific purpose. Sure, misuse of that purpose makes for a bad design, but automatically assuming all Sleep()'s are bad is in itself, a bad thing!
    • BlueM
      BlueM over 12 years
      In most cases it is used in a bad design. I've seen it hundred times. I cant think of a case where it would be "required" to use.
    • Sean U
      Sean U over 12 years
      The problem is, its specific purpose is to prevent the OS from scheduling the thread for a certain amount of time. This is rarely something that actually needs to be done in the real world. More commonly the requirement is waiting on something: I/O, another thread, some event, etc. In .NET and Java there are cleaner ways to do each of these than using Sleep(), which does something else and therefore needs to be wrapped in Rube Goldberg code to accomplish those tasks.
    • Martin James
      Martin James over 12 years
      'This is rarely something that actually needs to be done in the real world' really? You have never read a spec for anything that says 'wait at least ten seconds before continuing'?
    • Sean U
      Sean U over 12 years
      Sure I have. And in my experience it's generally a "spec smell".
  • ediblecode
    ediblecode over 12 years
    If you were ever going to program something like that, wouldn't you just use a timer?
  • Brian Rasmussen
    Brian Rasmussen over 12 years
    Just to add: And don't attempt to build an accurate timer with Thread.Sleep either.
  • Servy
    Servy over 12 years
    +1 it has lots of non-production code uses. It's also useful to demonstrate long running tasks when developing/demonstrating multithreaded frameworks etc. knowing that it's just a stand in for real work.
  • ediblecode
    ediblecode over 12 years
    This answer offers no answer to the question.
  • BlueM
    BlueM over 12 years
    I want to tell you that you should never use Thread.Sleep and better use event mechanisms. Thats my answer to your question, maybe it was not clear.
  • Matthew
    Matthew over 12 years
    I use Thread.Sleep on a background thread while performing long processing on a set of files or a network socket (and make a callback when the thread is completed). Is this a good use for Thread.Sleep or is there a better machanism to do this?
  • BlueM
    BlueM over 12 years
    And like mentioned in an answer above in msmvps.com/blogs/peterritchie/archive/2007/04/26/… it is indeed a sign of bad design. "In .NET there's no other reason to use it."
  • Sean U
    Sean U over 12 years
    @Matthew Sounds like you might be using two threads to do one thread's worth of work. Does the sleeping thread do anything aside from periodically wake up and check to see if a worker thread is still working? Can't the worker thread invoke the callback itself when it's done?
  • adelphus
    adelphus over 12 years
    +1 for describing exactly what Sleep() is designed for! It's irrelevant if the code is testing, production or otherwise. If you simply need a delay in a background thread, Sleep() is the way to go.
  • Martin James
    Martin James over 12 years
    I've read that linked article before. I just read it again. It was bad. It as worse the second time around.
  • Martin James
    Martin James over 12 years
    +1 for not reinforcing the, by now somewhat annoying, 'sleep is always bad' mantra. I'm sure that many developers have taken that on board and are now trying to debug complex, asychronous, timer-and-other-event driven state-machines instead of the simple, procedural code, with sleep() for waits, they were going to run in one thread.
  • Martin James
    Martin James over 12 years
    Timers force developers to develop state-machines to implement procedural specs. If an operation is defined by sequences of simpler stages, often separated by long intervals, function calls and sleep() calls map to this directly. An asynchronous state-machine does not.
  • Martin James
    Martin James over 12 years
    How do you use a timer to replace a sleep() call? Suppose you are in a 3rd-party script-interpreter 'OnProcessLine' event, an unknown depth down on the stack of one of several threads running different scripts, and you wish to pause for 10ms. How do you do that with a timer?
  • Martin James
    Martin James over 12 years
    'Complaints about using sleep usually related to effective (or rather ineffective) multi-threading design.' This is very true but, sadly, this translates in some minds into 'Sleep() is an anti-pattern'. 'Every year, fire tenders, ambulances and cop cruisers cause hundreds of traffic accidents - they should therefore all be banned'.
  • Matthew
    Matthew over 12 years
    @SeanU What I'm currently doing is having a thread do an network request, getting content and then having it make a callback when finished. In the loop where I poll the socket I call Thread.Sleep so it doesn't use 100% cpu usage and bring my application to a halt.
  • Martin James
    Martin James over 12 years
    @Matthew - that sounds like the 'misuse' category, I'm afraid :( Common socket operations like accept/read/write do not require polling.