Thread.Sleep is NOT evil
-
Some argue Thread.Sleep is evil - [^] Thread.Sleep is one-line of code, simple, and get the job done. I must say I disagree with the author of this ... discussion referenced. SCENARIO 1 - wait for async task completion: I agree that WaitHandle/Auto|ManualResetEvent should be used in scenario where a thread is waiting for task on another thread to complete. SCENARIO 2 - humble timing while loop: However, as a crude timing mechanism (while+Thread.Sleep) is perfectly fine for 99% of applications which does NOT require knowing exactly when the blocked Thread should "wake up*. The argument that it takes 200k cycles to create the thread is also invalid - the timing loop thread needs be created anyway and 200k cycles is just another big number (tell me how many cycles to open a file/socket/db calls?). So if while+Thread.Sleep works, why complicate things?
dev
-
Some argue Thread.Sleep is evil - [^] Thread.Sleep is one-line of code, simple, and get the job done. I must say I disagree with the author of this ... discussion referenced. SCENARIO 1 - wait for async task completion: I agree that WaitHandle/Auto|ManualResetEvent should be used in scenario where a thread is waiting for task on another thread to complete. SCENARIO 2 - humble timing while loop: However, as a crude timing mechanism (while+Thread.Sleep) is perfectly fine for 99% of applications which does NOT require knowing exactly when the blocked Thread should "wake up*. The argument that it takes 200k cycles to create the thread is also invalid - the timing loop thread needs be created anyway and 200k cycles is just another big number (tell me how many cycles to open a file/socket/db calls?). So if while+Thread.Sleep works, why complicate things?
dev
devvvy wrote:
Thread.Sleep is one-line of code, simple, and get the job done
Just because it's simple to implement, this doesn't mean it's a good choice. I recommend against
Thread.Sleep
precisely because of what it does - it suspends a thread for a timeout period. That doesn't seem too bad if you want to wait for a period, but the big problem comes when you want to terminate that thread. When a thread is sleeping, terminating it isn't easy - effectively, you have to wait for the thread to wake up just to kill it. This may not seem to be too big a deal, but if your system relies on having a number of these internally, you have just forced the user to wait and that's generally not a good thing. The primary reason that I recommend against it is precisely because it's so easy to use. The problem is, people end up using it as a blunt object and force it into programs that it shouldn't be in, precisely because they don't understand the downsides. If you fully appreciate the tradeoffs inThread.Sleep
then, by all means, use it. Don't, however, put it into code that a noob is going to read - as they probably don't appreciate the underlying issues withThread.Sleep
then they will blindly use it. There are other, subtle, problems with the use of Thread.Sleep, with relation to priority. A simple pattern, though, is simply to use Monitor.Enter to control the access, and this is my preferred choice in a lot of cases.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 -
devvvy wrote:
Thread.Sleep is one-line of code, simple, and get the job done
Just because it's simple to implement, this doesn't mean it's a good choice. I recommend against
Thread.Sleep
precisely because of what it does - it suspends a thread for a timeout period. That doesn't seem too bad if you want to wait for a period, but the big problem comes when you want to terminate that thread. When a thread is sleeping, terminating it isn't easy - effectively, you have to wait for the thread to wake up just to kill it. This may not seem to be too big a deal, but if your system relies on having a number of these internally, you have just forced the user to wait and that's generally not a good thing. The primary reason that I recommend against it is precisely because it's so easy to use. The problem is, people end up using it as a blunt object and force it into programs that it shouldn't be in, precisely because they don't understand the downsides. If you fully appreciate the tradeoffs inThread.Sleep
then, by all means, use it. Don't, however, put it into code that a noob is going to read - as they probably don't appreciate the underlying issues withThread.Sleep
then they will blindly use it. There are other, subtle, problems with the use of Thread.Sleep, with relation to priority. A simple pattern, though, is simply to use Monitor.Enter to control the access, and this is my preferred choice in a lot of cases.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 easierSCENARIO 1 - wait for task completion on another thread: I agree as I stated earlier not to use Thread.Sleep and that it's just outright wrong to do so. SCENARIO 2 - humble timing while loop: I'm not hearing any reason not to use it. As indicated * just because it's simple doesn't mean it's inappropriate * the thread which host the while loop needs be created anyway so thread creation cost is irrelevant * most applications don't need to know when *exactly* the blocked thread needs to *wake* up after specified period * alternative is to use a timer+event/subscriber which does nothing more than complicate an otherwise cannot-be-simpler while loop with a Thread.Sleep SCENARIO 3 Thread.Sleep(MagicDuration) or app breaks - well... this is a bug which demands correction in the first place. I'm not hearing any new argument in support of not using Thread.Sleep in SCENARIO 2 - - SCENARIO 1/3 is just plain stupid for anyone to use Thread.Sleep - SCENARIO 2 not using simple Thread.Sleep is just waste of *my* time This is an over discussed subject, gives people wrong impression this is actually complicated, that Thread.Sleep is really evil.
dev
-
devvvy wrote:
Thread.Sleep is one-line of code, simple, and get the job done
Just because it's simple to implement, this doesn't mean it's a good choice. I recommend against
Thread.Sleep
precisely because of what it does - it suspends a thread for a timeout period. That doesn't seem too bad if you want to wait for a period, but the big problem comes when you want to terminate that thread. When a thread is sleeping, terminating it isn't easy - effectively, you have to wait for the thread to wake up just to kill it. This may not seem to be too big a deal, but if your system relies on having a number of these internally, you have just forced the user to wait and that's generally not a good thing. The primary reason that I recommend against it is precisely because it's so easy to use. The problem is, people end up using it as a blunt object and force it into programs that it shouldn't be in, precisely because they don't understand the downsides. If you fully appreciate the tradeoffs inThread.Sleep
then, by all means, use it. Don't, however, put it into code that a noob is going to read - as they probably don't appreciate the underlying issues withThread.Sleep
then they will blindly use it. There are other, subtle, problems with the use of Thread.Sleep, with relation to priority. A simple pattern, though, is simply to use Monitor.Enter to control the access, and this is my preferred choice in a lot of cases.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 easierThis isn't meant as a sarcastic reply but one of learning. What would you recommend as a better method of doing the same as
thread.sleep
inside a thread?Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch
-
Some argue Thread.Sleep is evil - [^] Thread.Sleep is one-line of code, simple, and get the job done. I must say I disagree with the author of this ... discussion referenced. SCENARIO 1 - wait for async task completion: I agree that WaitHandle/Auto|ManualResetEvent should be used in scenario where a thread is waiting for task on another thread to complete. SCENARIO 2 - humble timing while loop: However, as a crude timing mechanism (while+Thread.Sleep) is perfectly fine for 99% of applications which does NOT require knowing exactly when the blocked Thread should "wake up*. The argument that it takes 200k cycles to create the thread is also invalid - the timing loop thread needs be created anyway and 200k cycles is just another big number (tell me how many cycles to open a file/socket/db calls?). So if while+Thread.Sleep works, why complicate things?
dev
I haven't read the article at all, but I'll give you another reason why it's evil. Every once in a while, you can get this little cryptic error message and you've got absolutely no clue as to what it means or why you're getting it: "The CLR has been unable to transition from COM context #x###### to COM context #x###### for 60 seconds. The thread that owns the destination context/apartment...blah blah blah" Why does this happen?? Well, you get this mesage onyl when running under the debugger. Usually it's because Thread.Sleep has been called for greater than 60 seconds or there is a long running operation going on on a thread hosting a message pump. STA COM is accomplished through message passing and if those message don't get processed ... kaboom!
A guide to posting questions on CodeProject[^]
Dave Kreskowiak -
SCENARIO 1 - wait for task completion on another thread: I agree as I stated earlier not to use Thread.Sleep and that it's just outright wrong to do so. SCENARIO 2 - humble timing while loop: I'm not hearing any reason not to use it. As indicated * just because it's simple doesn't mean it's inappropriate * the thread which host the while loop needs be created anyway so thread creation cost is irrelevant * most applications don't need to know when *exactly* the blocked thread needs to *wake* up after specified period * alternative is to use a timer+event/subscriber which does nothing more than complicate an otherwise cannot-be-simpler while loop with a Thread.Sleep SCENARIO 3 Thread.Sleep(MagicDuration) or app breaks - well... this is a bug which demands correction in the first place. I'm not hearing any new argument in support of not using Thread.Sleep in SCENARIO 2 - - SCENARIO 1/3 is just plain stupid for anyone to use Thread.Sleep - SCENARIO 2 not using simple Thread.Sleep is just waste of *my* time This is an over discussed subject, gives people wrong impression this is actually complicated, that Thread.Sleep is really evil.
dev
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 useSystem.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. WhereSystem.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 whereThread.Sleep()
is not the right solution. Any statement which saysThread.Sleep()
is evil without understanding the context where it is used is STUPID.Best wishes, Navaneeth
-
This isn't meant as a sarcastic reply but one of learning. What would you recommend as a better method of doing the same as
thread.sleep
inside a thread?Lobster Thermidor aux crevettes with a Mornay sauce, served in a Provençale manner with shallots and aubergines, garnished with truffle pate, brandy and a fried egg on top and Spam - Monty Python Spam Sketch
Simon_Whale wrote:
What would you recommend as a better method of doing the same as
thread.sleep
inside a thread?If you want to run a job which executes in every 'n' minutes, you can use
System.Threading.Timer
. If you want to wait till another thread finishes execution, you can use WaitHandle. If you just want to sleep, useThread.Sleep()
:)Best wishes, Navaneeth
-
SCENARIO 1 - wait for task completion on another thread: I agree as I stated earlier not to use Thread.Sleep and that it's just outright wrong to do so. SCENARIO 2 - humble timing while loop: I'm not hearing any reason not to use it. As indicated * just because it's simple doesn't mean it's inappropriate * the thread which host the while loop needs be created anyway so thread creation cost is irrelevant * most applications don't need to know when *exactly* the blocked thread needs to *wake* up after specified period * alternative is to use a timer+event/subscriber which does nothing more than complicate an otherwise cannot-be-simpler while loop with a Thread.Sleep SCENARIO 3 Thread.Sleep(MagicDuration) or app breaks - well... this is a bug which demands correction in the first place. I'm not hearing any new argument in support of not using Thread.Sleep in SCENARIO 2 - - SCENARIO 1/3 is just plain stupid for anyone to use Thread.Sleep - SCENARIO 2 not using simple Thread.Sleep is just waste of *my* time This is an over discussed subject, gives people wrong impression this is actually complicated, that Thread.Sleep is really evil.
dev
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 -
Some argue Thread.Sleep is evil - [^] Thread.Sleep is one-line of code, simple, and get the job done. I must say I disagree with the author of this ... discussion referenced. SCENARIO 1 - wait for async task completion: I agree that WaitHandle/Auto|ManualResetEvent should be used in scenario where a thread is waiting for task on another thread to complete. SCENARIO 2 - humble timing while loop: However, as a crude timing mechanism (while+Thread.Sleep) is perfectly fine for 99% of applications which does NOT require knowing exactly when the blocked Thread should "wake up*. The argument that it takes 200k cycles to create the thread is also invalid - the timing loop thread needs be created anyway and 200k cycles is just another big number (tell me how many cycles to open a file/socket/db calls?). So if while+Thread.Sleep works, why complicate things?
dev
There is one case in which I have used it where it is actually useful to slow things down for the user. The case in point is an update to an application - sometimes the update is so small that all the user would see is a number of dialogues and progress bars flashing on the screen leaving them to wonder if the update has taken place. So I introduced a four second sleep in order to allow the user to see that something was happening. It has saved me from having to say "yes the update did take place, it was just very small" - that comfortable warm feeling is very important to the user.
“That which can be asserted without evidence, can be dismissed without evidence.”
― Christopher Hitchens
-
Some argue Thread.Sleep is evil - [^] Thread.Sleep is one-line of code, simple, and get the job done. I must say I disagree with the author of this ... discussion referenced. SCENARIO 1 - wait for async task completion: I agree that WaitHandle/Auto|ManualResetEvent should be used in scenario where a thread is waiting for task on another thread to complete. SCENARIO 2 - humble timing while loop: However, as a crude timing mechanism (while+Thread.Sleep) is perfectly fine for 99% of applications which does NOT require knowing exactly when the blocked Thread should "wake up*. The argument that it takes 200k cycles to create the thread is also invalid - the timing loop thread needs be created anyway and 200k cycles is just another big number (tell me how many cycles to open a file/socket/db calls?). So if while+Thread.Sleep works, why complicate things?
dev
-
There is one case in which I have used it where it is actually useful to slow things down for the user. The case in point is an update to an application - sometimes the update is so small that all the user would see is a number of dialogues and progress bars flashing on the screen leaving them to wonder if the update has taken place. So I introduced a four second sleep in order to allow the user to see that something was happening. It has saved me from having to say "yes the update did take place, it was just very small" - that comfortable warm feeling is very important to the user.
“That which can be asserted without evidence, can be dismissed without evidence.”
― Christopher Hitchens
Or something like this:
public class Utility
{
private static readonly object SyncLock = new object();public void WaitForTime(int milliseconds)
{
lock (SyncLock)
{
Monitor.Wait(SyncLock, milliseconds);
}
}public WakeAllThreads()
{
lock (SyncLock)
{
Monitor.PulseAll(SyncLock);
}
}
}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 -
Or something like this:
public class Utility
{
private static readonly object SyncLock = new object();public void WaitForTime(int milliseconds)
{
lock (SyncLock)
{
Monitor.Wait(SyncLock, milliseconds);
}
}public WakeAllThreads()
{
lock (SyncLock)
{
Monitor.PulseAll(SyncLock);
}
}
}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 easierThanks Pete! Much appreciated :) I shall now use that method - it would be nice if Microsoft deprecated the sleep method so that people like me were prevented from using it.
“That which can be asserted without evidence, can be dismissed without evidence.”
― Christopher Hitchens
-
Or something like this:
public class Utility
{
private static readonly object SyncLock = new object();public void WaitForTime(int milliseconds)
{
lock (SyncLock)
{
Monitor.Wait(SyncLock, milliseconds);
}
}public WakeAllThreads()
{
lock (SyncLock)
{
Monitor.PulseAll(SyncLock);
}
}
}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 -
Why is that better? Actually isn't that worse because when you call WakeAllThreads it will wait on the lock and your app will be unresponsive in all threads (including the one you're sending a wakeup call from)?
That's just a paste of some code I use to wake things up to kill all the threads (this is the scenario I talk about above). Monitor has a simple Pulse method as well to wake a single thread before the timeout expires.
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 -
Let's not ;)
Dave
Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn) -
I haven't read the article at all, but I'll give you another reason why it's evil. Every once in a while, you can get this little cryptic error message and you've got absolutely no clue as to what it means or why you're getting it: "The CLR has been unable to transition from COM context #x###### to COM context #x###### for 60 seconds. The thread that owns the destination context/apartment...blah blah blah" Why does this happen?? Well, you get this mesage onyl when running under the debugger. Usually it's because Thread.Sleep has been called for greater than 60 seconds or there is a long running operation going on on a thread hosting a message pump. STA COM is accomplished through message passing and if those message don't get processed ... kaboom!
A guide to posting questions on CodeProject[^]
Dave Kreskowiak -
Simon_Whale wrote:
What would you recommend as a better method of doing the same as
thread.sleep
inside a thread?If you want to run a job which executes in every 'n' minutes, you can use
System.Threading.Timer
. If you want to wait till another thread finishes execution, you can use WaitHandle. If you just want to sleep, useThread.Sleep()
:)Best wishes, Navaneeth
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
-
Let's not ;)
Dave
Binging is like googling, it just feels dirtier. Please take your VB.NET out of our nice case sensitive forum. Astonish us. Be exceptional. (Pete O'Hanlon)
BTW, in software, hope and pray is not a viable strategy. (Luc Pattyn) -
Thanks Pete! Much appreciated :) I shall now use that method - it would be nice if Microsoft deprecated the sleep method so that people like me were prevented from using it.
“That which can be asserted without evidence, can be dismissed without evidence.”
― Christopher Hitchens
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? M$ probably deprecate Thread.Sleep either because its syntax laywer told him so or simply it isn't "cool"
dev
-
No, it's not. Do you know how times I've seen Thread.Sleep show up on the UI thread?? LOTS!
A guide to posting questions on CodeProject[^]
Dave Kreskowiak