Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. Thread.Sleep is NOT evil

Thread.Sleep is NOT evil

Scheduled Pinned Locked Moved C#
databasecomquestiondiscussioncareer
42 Posts 9 Posters 4 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • D devvvy

    still - there's nothing against SCENARIO 2, if it's not a UI thread or one with a message pump. Thread.Sleep isn't evil - it's just uncool. It's uncool because most developers tell each other it's uncool to do so.

    dev

    D Offline
    D Offline
    Dave Kreskowiak
    wrote on last edited by
    #26

    OK, it's "uncool" because most people (noobs) use it like they use PictureBox. They use it without knowing it's limitations and without knowing that there are far better alternatives to it.

    A guide to posting questions on CodeProject[^]
    Dave Kreskowiak

    D 1 Reply Last reply
    0
    • P Pete OHanlon

      devvvy wrote:

      THUS FAR there isn't ONE SINGLE argument that justify against use of Thread.Sleep against SCENARIO 2.

      Errm. Yes, we have posted arguments against, you're just choosing to ignore them. As for the reason I show Monitor.Wait is that it is close to the behaviour you're after with your Thread.Sleep, in that it puts the ThreadState into WaitSleepJoin, but it doesn't yield the thread to the OS. This is an important point because you can wake this thread up if you need to. This is the point you seem to be missing. Thread.Sleep - there is no wake up, other than through a Thread.Abort and we've already covered how that makes things unpredicable - if you need to cancel the thread and have it tidy itself up you have to wait for it to wake up. Also, Dave has a very valid point about the behaviour in STA COM. In this scenario, again, this is a justification that Thread.Sleep should not be used. It is not the appropriate mechanism.

      I was brought up to respect my elders. I don't respect many people nowadays.
      CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

      N Offline
      N Offline
      N a v a n e e t h
      wrote on last edited by
      #27

      Pete O'Hanlon wrote:

      Errm. Yes, we have posted arguments against, you're just choosing to ignore them.

      I second that. He don't have the maturity to understand what people are saying. So no point in discussing further. :)

      Best wishes, Navaneeth My blog

      D 1 Reply Last reply
      0
      • D devvvy

        sure as i pointed out earlier timer/event subscriber - but why bother. THUS FAR there isn't ONE SINGLE argument that justify against use of Thread.Sleep against SCENARIO 2. I hereby invite you synatex lawyers/bitches to put forth your challenge to overthrow this hypothesis.

        dev

        N Offline
        N Offline
        N a v a n e e t h
        wrote on last edited by
        #28

        devvvy wrote:

        THUS FAR there isn't ONE SINGLE argument that justify against use of Thread.Sleep against SCENARIO 2.

        As Pete already told, you are ignoring the comments that we made for Scenario2. See my answer.

        Best wishes, Navaneeth My blog

        D 1 Reply Last reply
        0
        • P Pete OHanlon

          devvvy wrote:

          THUS FAR there isn't ONE SINGLE argument that justify against use of Thread.Sleep against SCENARIO 2.

          Errm. Yes, we have posted arguments against, you're just choosing to ignore them. As for the reason I show Monitor.Wait is that it is close to the behaviour you're after with your Thread.Sleep, in that it puts the ThreadState into WaitSleepJoin, but it doesn't yield the thread to the OS. This is an important point because you can wake this thread up if you need to. This is the point you seem to be missing. Thread.Sleep - there is no wake up, other than through a Thread.Abort and we've already covered how that makes things unpredicable - if you need to cancel the thread and have it tidy itself up you have to wait for it to wake up. Also, Dave has a very valid point about the behaviour in STA COM. In this scenario, again, this is a justification that Thread.Sleep should not be used. It is not the appropriate mechanism.

          I was brought up to respect my elders. I don't respect many people nowadays.
          CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

          D Offline
          D Offline
          devvvy
          wrote on last edited by
          #29

          1. As I pointed out earlier, there's no need to know *exact* when the blocked thread wakes up again. 2. STA COM debug messages -> how's debug messages in debug mode in a thread with a message pump affect me if all i've got is a non-ui baclground thread?

          dev

          P 1 Reply Last reply
          0
          • N N a v a n e e t h

            devvvy wrote:

            THUS FAR there isn't ONE SINGLE argument that justify against use of Thread.Sleep against SCENARIO 2.

            As Pete already told, you are ignoring the comments that we made for Scenario2. See my answer.

            Best wishes, Navaneeth My blog

            D Offline
            D Offline
            devvvy
            wrote on last edited by
            #30

            i pointed out timer + event handler as an alternative in the first place, but it's more lines of code for no additional benefit than a simple while+Sleep

            dev

            1 Reply Last reply
            0
            • D Dave Kreskowiak

              OK, it's "uncool" because most people (noobs) use it like they use PictureBox. They use it without knowing it's limitations and without knowing that there are far better alternatives to it.

              A guide to posting questions on CodeProject[^]
              Dave Kreskowiak

              D Offline
              D Offline
              devvvy
              wrote on last edited by
              #31

              it's a simple reliable picture box. if people use it for SCENARIO 1/3 it's just absurb in the first place. but SCENARIO 2 it's just not much to talk about - the fact there is simply because people wasting each other time trying to complicate otherwise very simple Thread.Sleep

              dev

              D 1 Reply Last reply
              0
              • G GuyThiebaut

                devvvy wrote:

                why the appreciation? It's more code than a simple while loop with a Sleep.   why you want be thankful when there really isn't a justification for it?

                Because someone, especially as it is a person I don't personally know, went out of their way to offer me help. In my books that deserves my appreciation ;)

                “That which can be asserted without evidence, can be dismissed without evidence.”

                ― Christopher Hitchens

                D Offline
                D Offline
                devvvy
                wrote on last edited by
                #32

                right, but do you see the point on why you need replace Thread.Sleep for SCENARIO 2 with ten more lines of code (re-implement with Timer+Event handler)? If no, your *thank you* will confuse other users for taking that really "Thread.Sleep" is evil, casting further confusion and un-necessary complication on this otherwise simple subject (You should thank those syntax lawyers for this). That's how we never get to bottom of things

                dev

                1 Reply Last reply
                0
                • P Pete OHanlon

                  devvvy wrote:

                  why the appreciation? It's more code than a simple while loop with a Sleep.

                  So, you think he has to write this out every time? Chuck it in a library and you're done - a simple

                  new Utility().WaitForTime(5000);

                  I was brought up to respect my elders. I don't respect many people nowadays.
                  CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

                  D Offline
                  D Offline
                  devvvy
                  wrote on last edited by
                  #33

                  Peter - this is nice/good idea. But this detracts the discussion to get to the bottom: SCENARIO 1/3 is just plain stupid to use Thread.Sleep - so just forget it. SCENARIO 2 - there's yet one single real justification to establish "Thread.Sleep" is *Evil* (as i pointed out in very beginning timer+event handler *can* be alternative - but why bother)

                  dev

                  P 1 Reply Last reply
                  0
                  • N N a v a n e e t h

                    Pete O'Hanlon wrote:

                    Errm. Yes, we have posted arguments against, you're just choosing to ignore them.

                    I second that. He don't have the maturity to understand what people are saying. So no point in discussing further. :)

                    Best wishes, Navaneeth My blog

                    D Offline
                    D Offline
                    devvvy
                    wrote on last edited by
                    #34

                    there's no point because you're still confused SCENARIO 2 a simple background thread with a while+Sleep with no UI pump, with SCENARIO 1/3 you ran out of further arguments don't you?

                    dev

                    1 Reply Last reply
                    0
                    • N N a v a n e e t h

                      Thread.Sleep() is not EVIL if you know how it works and if that's the behavior that you really want to accomplish. The reason people say it is evil because they use it wrongly without understanding how it works.

                      devvvy wrote:

                      SCENARIO 2 - humble timing while loop: I'm not hearing any reason not to use it. As indicated

                      If your application doesn't care about accuracy of the execution ineterval, then Thread.Sleep() is alright to use. Let us say you need to execute some task every minute and you start the application at 10AM. It is supposed to execute at 10.01, 10.02, 10.03 etc. You'd write something like,

                      while(!exit)
                      {
                      // Do your job
                      Thread.Sleep(10000);
                      }

                      What happens if your job takes more than 1 minute? Then the next run which was supposed to happen at 10.01 won't happen. This delays the next execution too. With this design, it will be hard to tell when the next run will happen. If this behavior is alright for your application, there is no problem in using Thread.Sleep(). To workaround this problem, you can use System.Threading.Timer to schedule the job. It gives a better scheduling capabilities and executes the job exactly at the interval that you specify. Timer callback method can be executed simultaneously by multiple threads if the job takes more time than the interval. This increases parallelism and makes the processing faster. It is also logical to think that why do you need to waste a thread by just sleeping? The wastage could be minimal, but it is a wastage. Where System.Threading.Timer uses thread pool threads and thread pools are more optimized for better usage of resources. Thread pools are initialized with a set of threads when the application domain starts.

                      devvvy wrote:

                      This is an over discussed subject, gives people wrong impression this is actually complicated, that Thread.Sleep is really evil.

                      It's about maturity. If you know how Thread.Sleep() works then you'd probably use it correctly and use alternatives where Thread.Sleep() is not the right solution. Any statement which says Thread.Sleep() is evil without understanding the context where it is used is STUPID.

                      Best wishes, Navaneeth

                      D Offline
                      D Offline
                      devvvy
                      wrote on last edited by
                      #35

                      To overthrow the uneducated accusation on Thread.Sleep from self righteous syntax high priests (but i pointed out very beginning timer/handler as alternative + exactly when next loop gets executed is un-important for 99% of the apps)

                      dev

                      1 Reply Last reply
                      0
                      • D devvvy

                        1. As I pointed out earlier, there's no need to know *exact* when the blocked thread wakes up again. 2. STA COM debug messages -> how's debug messages in debug mode in a thread with a message pump affect me if all i've got is a non-ui baclground thread?

                        dev

                        P Offline
                        P Offline
                        Pete OHanlon
                        wrote on last edited by
                        #36

                        devvvy wrote:

                        1. As I pointed out earlier, there's no need to know *exact* when the blocked thread wakes up again.

                        There is if you're trying to shut down an application. I don't know how many times I can point out the same thing; perhaps with a simple example - you have a service with a thread that needs to clean up before the service can shut down - by having to wait for the thread to finish, you could trigger the "Service could not be stopped, blah blah blah" message. I have seen this happen many times, and it's always been because someone who doesn't know any better has decided that a simple one liner is better then something that behaves cleanly. If you know what you're doing, and if you're well informed about the pitfalls in Thread.Sleep, and if you've thought through the implications then by all means, use Thread.Sleep. If you can't claim all of these conditions, then look for a safer alternative - one that won't leave your users wanting to hang you by your testicles when you inconvenience them because you couldn't be bothered to type in three lines.

                        I was brought up to respect my elders. I don't respect many people nowadays.
                        CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

                        D 1 Reply Last reply
                        0
                        • P Pete OHanlon

                          In scenario 2, you're confusing the need to create the thread with the need to use it as a timer. If you need to use something as a timer, then why not use a timer? However, this case is the one that is potentially the most dangerous. Suppose that your application creates 10 threads and then puts them to sleep for 30 seconds, and each thread has opened up some resources that must be disposed of when the thread completes. Now, suppose that 2 seconds into this, your application wants to close - what do you think the effect will be? The reason that it's so discussed is that it does have drawbacks, and it can be inherently risky. It's very simplicity is what makes it so attractive, and it can end up being used when it is inappropriate to do so because you don't appreciate the subtleties involved in using it. Threading and multi-tasking is not an easy thing to get right, it really isn't. As I said earlier, using it when you know exactly what goes on with it is fine, it's when you don't understand the drawbacks that it's a problem. And using something because it's slightly less typing than the alternatives is just lazy programming - don't use something because it saves you a few keystrokes, use the tool that is right and appropriate.

                          I was brought up to respect my elders. I don't respect many people nowadays.
                          CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

                          D Offline
                          D Offline
                          devvvy
                          wrote on last edited by
                          #37

                          Pete O'Hanlon wrote:

                          then why not use a timer?

                          because there's no reason to - as 99% of app don't need to know exactly when next while loop get executed, so why complicate things which are otherwise simpler? it's as *dangerous* as not knowing exactly when next loop get executed which 99% of applications don't care/matter

                          Pete O'Hanlon wrote:

                          it's so discussed is that it does have drawbacks, and it can be inherently risky. I

                          Using Thread.Sleep for SCENARIO 1/3 is just plain wrong. This complicates the otherwise simple discussion. Things which are simple should remain simple.

                          Pete O'Hanlon wrote:

                          don't use something because it saves you a few keystrokes, use the tool that is right and appropriate.

                          But I was just contemplating using your suggestion wrapping timer into a single line function. As I do agree - after you wrap it to single line, a. it's as simple as thread.sleep b. now you know exactly when next execution happens

                          Pete O'Hanlon wrote:

                          Suppose that your application creates 10 threads and then puts them to sleep for 30 seconds, and each thread has opened up some resources that must be disposed of when the thread completes. Now, suppose that 2 seconds into this, your application wants to close - what do you think the effect will be?

                          This is a Thread.Abort or App Exit clean up issue, not Thread.Sleep issue - it's always bad to forcefully terminate app/threads. I take what you mean as following? try { while(true) { using(Stream...) { ... Thread.Sleep(#1) <-- What would happen? indeterministic } <-- Dispose here anyway as "using" translated to try-finally (But what if aborted during finally) Thread.Sleep(#2) <-- fine already disposed } catch(ThreadAbortEx) { } finally{ }

                          dev

                          1 Reply Last reply
                          0
                          • D devvvy

                            Peter - this is nice/good idea. But this detracts the discussion to get to the bottom: SCENARIO 1/3 is just plain stupid to use Thread.Sleep - so just forget it. SCENARIO 2 - there's yet one single real justification to establish "Thread.Sleep" is *Evil* (as i pointed out in very beginning timer+event handler *can* be alternative - but why bother)

                            dev

                            P Offline
                            P Offline
                            Pete OHanlon
                            wrote on last edited by
                            #38

                            devvvy wrote:

                            But this detracts the discussion to get to the bottom

                            No it doesn't. It shows alternatives. The reason people are using the term "Evil" (and I think this is the word you're getting hung up on) is because threading isn't easy. It isn't trivial. But Thread.Sleep makes it appear as though it is because it's a convenience to hide the complexity, and sooner or later, this complexity creeps out and rips your face clean off. Subtle bugs creep in and they are hugely difficult to track down because they are timing based, and that timing is not predictable, because Thread.Sleep isn't predictable. The OS can actually do different things depending on what you've done with it.

                            I was brought up to respect my elders. I don't respect many people nowadays.
                            CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

                            D 1 Reply Last reply
                            0
                            • P Pete OHanlon

                              devvvy wrote:

                              1. As I pointed out earlier, there's no need to know *exact* when the blocked thread wakes up again.

                              There is if you're trying to shut down an application. I don't know how many times I can point out the same thing; perhaps with a simple example - you have a service with a thread that needs to clean up before the service can shut down - by having to wait for the thread to finish, you could trigger the "Service could not be stopped, blah blah blah" message. I have seen this happen many times, and it's always been because someone who doesn't know any better has decided that a simple one liner is better then something that behaves cleanly. If you know what you're doing, and if you're well informed about the pitfalls in Thread.Sleep, and if you've thought through the implications then by all means, use Thread.Sleep. If you can't claim all of these conditions, then look for a safer alternative - one that won't leave your users wanting to hang you by your testicles when you inconvenience them because you couldn't be bothered to type in three lines.

                              I was brought up to respect my elders. I don't respect many people nowadays.
                              CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

                              D Offline
                              D Offline
                              devvvy
                              wrote on last edited by
                              #39

                              Pete O'Hanlon wrote:

                              There is if you're trying to shut down an application. I don't know how many times I can point out the same thing; perhaps with a simple example - you have a service with a thread that needs to clean up before the service can shut down - by having to wait for the thread to finish, you could trigger the "Service could not be stopped, blah blah blah" message.

                              My apologies Pete - this is something we'd run into if we're not careful with SCENARIO 2 if Thread.Sleep(LONGTIME) (where timer/handler would have avoided this). Having consider this, Thread.Sleep even for SCENARIO 2 may likely to cause problem in app exit if not used carefully. I don't think this very important argument has nearly enough visibility in this discussion/other places. Thanks Pete! Thread.Sleep is Evil after all. (For SCENARIO 1,2,3) Sample to demo the issue as follows: static void Main(string[] args) { Thread t = new Thread(new ThreadStart(ThreadFunc)); t.Start(); Console.WriteLine("Hit any key to exit."); Console.ReadLine(); Console.WriteLine("App exiting"); return; } static void ThreadFunc() { int i=0; try { while (true) { Console.WriteLine(i); Thread.Sleep(1000 * 10); i++; } } finally { Console.WriteLine("Exiting while loop"); } return;

                              dev

                              1 Reply Last reply
                              0
                              • P Pete OHanlon

                                devvvy wrote:

                                But this detracts the discussion to get to the bottom

                                No it doesn't. It shows alternatives. The reason people are using the term "Evil" (and I think this is the word you're getting hung up on) is because threading isn't easy. It isn't trivial. But Thread.Sleep makes it appear as though it is because it's a convenience to hide the complexity, and sooner or later, this complexity creeps out and rips your face clean off. Subtle bugs creep in and they are hugely difficult to track down because they are timing based, and that timing is not predictable, because Thread.Sleep isn't predictable. The OS can actually do different things depending on what you've done with it.

                                I was brought up to respect my elders. I don't respect many people nowadays.
                                CodeStash - Online Snippet Management | My blog | MoXAML PowerToys | Mole 2010 - debugging made easier

                                D Offline
                                D Offline
                                devvvy
                                wrote on last edited by
                                #40

                                Thanks Pete - I saw your argument on application exit. Now I would conclude Thread.Sleep is evil for all SCENARIO 1,2,3 Big Thank you!

                                dev

                                1 Reply Last reply
                                0
                                • D devvvy

                                  it's a simple reliable picture box. if people use it for SCENARIO 1/3 it's just absurb in the first place. but SCENARIO 2 it's just not much to talk about - the fact there is simply because people wasting each other time trying to complicate otherwise very simple Thread.Sleep

                                  dev

                                  D Offline
                                  D Offline
                                  Dave Kreskowiak
                                  wrote on last edited by
                                  #41

                                  Oh but Thread.Sleep is not so simple. Using it has vast implications on the functionality of the rest of your app. That's why so many noobs use it and can't figure out why their app doesn't work properly or, as you mentioned, you can't shutdown a service without timing out the Service Manager.

                                  A guide to posting questions on CodeProject[^]
                                  Dave Kreskowiak

                                  D 1 Reply Last reply
                                  0
                                  • D Dave Kreskowiak

                                    Oh but Thread.Sleep is not so simple. Using it has vast implications on the functionality of the rest of your app. That's why so many noobs use it and can't figure out why their app doesn't work properly or, as you mentioned, you can't shutdown a service without timing out the Service Manager.

                                    A guide to posting questions on CodeProject[^]
                                    Dave Kreskowiak

                                    D Offline
                                    D Offline
                                    devvvy
                                    wrote on last edited by
                                    #42

                                    I saw two arguments against using Thread.Sleep for scenario 2 a. From you: Thread.Sleep screw up message pump IF you do this on UI Thread (But why'd you Thread.Sleep on UI in the first place!) b. From Pete: Application exit Both are valid arguments - But I don't think I stumble across these in other places at all. They deserve more visibility I now agree - Thread.Sleep is evil. (And can be replaced/avoided by one line timer+handler if you wrap it up in one blocking function call) Thank you!

                                    dev

                                    1 Reply Last reply
                                    0
                                    Reply
                                    • Reply as topic
                                    Log in to reply
                                    • Oldest to Newest
                                    • Newest to Oldest
                                    • Most Votes


                                    • Login

                                    • Don't have an account? Register

                                    • Login or register to search.
                                    • First post
                                      Last post
                                    0
                                    • Categories
                                    • Recent
                                    • Tags
                                    • Popular
                                    • World
                                    • Users
                                    • Groups