Thread.Sleep is a sign of a poorly designed program.

Thread.Sleep has it’sits use: simulating lengthy operations while testing/debugging on an MTA thread.  In .NET there’s no other reason to use it.

Thread.Sleep(n) means block the current thread for at least the number of timeslices (or thread quantums) that can occur within n milliseconds.  The length of a timeslice is different on different versions/types of Windows and different processors and generally ranges from 15 to 30 milliseconds.  This means the thread is almost guaranteed to block for more than n milliseconds.  The likelihood that your thread will re-awaken exactly after n milliseconds is about as impossible as impossible can be.  So, Thread.Sleep is pointless for timing.

Threads are a limited resource, they take approximately 200,000 cycles to create and about 100,000 cycles to destroy.  By default they reserve 1 megabyte of virtual memory for its stack and use 2,000-8,000 cycles for each context switch.  This makes any waiting thread a *huge* waste.

If the current thread is a foreground thread, Thread.Sleep(n) also means your application cannot exit for >n milliseconds.  After all foreground threads have completed, the CLR will allow an application to terminate.  If the current thread is a background thread, and the application exits the thread will simply never be awoken (not good if you need your objects to be disposed or finalized).

STA threads have an implicit requirement to not make blocking calls.  STA threads use a message queue (of finite size) to communicate with the outside world; that communication occurs whether you explicitly use it or not.  When you block your STA thread with Thread.Sleep you’re blocking that communication and run the risk of the queue overflowing.  A WinForm thread must be STA, so it has the same implicit requirement to not make blocking calls simply to support being an apartment.  A GUI should never make calls that can affect the responsiveness of the user interface, for obvious reasons.

There is one non-breaking use for Thread.Sleep: Thread.Sleep(0).  This tells the system you want to forfeit the rest of the thread’s timeslice and let another, waiting, thread run.  If there are no other threads waiting to run you still relinquish your timeslice.  If There are other threads waiting to run, you won’t be sure when you get control back; if the waiting thread has a higher priority, you may never get control back.  Thread.Sleep(0) effectively tells the OS that you’re better at scheduling processes than it is and you’ll likely affect the way it can schedule threads and processes and affect the responsiveness of the entire system if you’re using Sleep(0) a lot.

As future versions of the CLR and CLR hosts are implemented they will eventually implement threading without a direct dependence on unmanaged threads (e.g. managed entirely by the CLR using fibers.)  Which means Thread.Sleep will have to be reimplemented to do something different (e.g.i.e. if Sleep(0) means relinquish the current thread’s timeslice to the OS and there is no current OS thread then Sleep(0) means nothing.  If Thread.Sleep is not re-implemented Thread.Thread(0) means block all fibers, or managed threads, associated with the current OS thread.  You never want to cause other threads to suspend, especially arbitrarily).  So, System.Thread is not future-friendly.

Thread.Sleep has been used for many things it shouldn’t be used for.  Here’s a list of the common mistakes:

The thread needs to wait for another thread to complete
In this case no value, other than infinite, passed to Thread.Sleep will be correct.  You simply don’t know when the other thread will complete using this method.  If the thread completed after Sleep returned you’ll likely have synchronization problems.  If the other thread completed before Sleep returned the thread was needlessly blocked for an amount of time rendering the benefits of multithreading limited or moot.  In the control circumstances where you’ve tested this it may seem like it always works; it just takes a busy program to cause it to faile: a defrag program, a sudden influx of network traffic, a network hiccup, etc.

The thread needs perform logic every n milliseconds
As noted earlier, Sleep means relinquish control.  When your thread gets control again isn’t up to the thread; so it can’t be used for periodic logic.

We don’t know why Thread.Sleep is required; but if we take it out the application stops working
This is flawed logic because the application still doesn’t work with Thread.Sleep.  This is really just spackling over the problem on that particular computer.  The original problem is likely a timing/synchronization issue, ignoring it by hiding it with Thread.Sleep is only going to delay the problem and make it occur in random, hard to reproduce ways.

114 thoughts on “Thread.Sleep is a sign of a poorly designed program.

  1. More generally creating explicity threads is a sign of flawed design. You should always use threadpool thread, except in some very scarse situations (such as when you need to adjust thread priority or if you need some foreground threads).

    Here is a NDepend CQL constraint that can help pinpoints these flaws:

    WARN IF Count > 0 IN SELECT METHODS WHERE
    IsDirectlyUsing “System.Threading.Thread.Sleep(Int32)” OR
    DepthOfIsCreating “System.Threading.Thread” == 0

    Another good practice for multithreaded app is to use immutable types. Check out here:

    http://s3.amazonaws.com/NDependOnlineDemos/NDependMultiThreadedApp_viewlet_swf.html

    Patrick

  2. I use Thread.Sleep(x) to wait for hardware connected to PC to finish after I send it a comman. This is run in a BackgroundWorker Do Work routine as the last instruction. Given that I am waiting on something that is guaranteed to finish in x ms by hardware I can’t see the problem with using Thread.Sleep.

  3. RE: Explicitly created threads:

    It may be likely that it’s rare that explicitly created threads are being used correctly or optimally; but, there are many valid uses to explicitly created threads. That’s not the case with Thread.Sleep.

  4. RE: Thread.Sleep waiting for hardware. I’d have to see what hardware you’re talking about; but I’ve never seen any hardware driver guarantee completion of anything within x ms. So, that sounds suspect.

    Even if your driver does provide that guarantee, there’s no guarantee Thread.Sleep will awake after x ms; it’s likely much longer than x and it depends on the CPU/OS and load. Which means you’re guaranteed to have a period of time where your thread is waiting needlessly (i.e. you’ve overshoot the “real” time, if the driver completed after 5 ms but the system granularity is 10 ms your thread won’t awaken until >5ms after the hardware completed.)

    When communicating with hardware I recommend using Asynchronous IO in .NET or completion ports in native. That way your application is notified the moment the IO is completed, plus you don’t have to needlessly create a second thread simply for waiting (which is extremely un-scalable).

  5. You missed a point about Thread.Sleep(0). On a uniprocessor system this has no effect and you need to P/Invoke SwitchToThread. Otherwise, I agree – Thread.Sleep is bad. Not in the same league as Thread.Abort, but still bad.

  6. Thanks for this article!
    “The thread needs perform logic every n milliseconds” – under this header, you discouraged using the Sleep method also. What would be an alternative? Please note that, a Timer object can’t be used under the circumstances.
    Will greatly appreciate your insight into this!
    Best Regards!
    Raihan

  7. no doubt, it is :-), and I know very well, where in my programs are this beasts isolated :-)), preparing to kill them all ASAP :-), as I learn to use async delegates, thread pool, Begin/End calls, be sure 🙂

    I am smiling looking at most Delphi programs which are compiled into native code, but mostly behave quite unresponsive too … they are written often by people who hate .NET for its slowness, LOL

  8. I’m using Thread.Sleep quite effectively for displaying progress for a file download in a console app. I realise a console app is a simplest case scenario (and no need fro MTA), but if there’s a better way, I’d be interested to know what it is.

  9. I’m using Thread.Sleep quite effectively for displaying progress for a file download in a console app. I realise a console app is a simplest case scenario (and no need for MTA), but if there’s a better way, I’d be interested to know what it is.

  10. I use thread.sleep() while flashing an embbedded controller. I use the serialPort class data recieved event. There are a few times where I have to slow things down for the controller, the PC is too fast. Do not know any other way to do this.

  11. Generally you are right – at least when it comes to the UI thread, but there are a few exceptions where Sleep is the only resonable solution because of flawed event design.

    See the MSDN.VB.NET thread: “Why To Not Use Threading.Sleep in Your Application”:
    http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1896112&SiteID=1 ,where there is a very long discussion about this subject.

    I don’t see Sleep as a future problem. Of course the ones, who implement future versions, must ensure that Sleep still works the way it is expected to do and not blocks other threads.

  12. @CarstenK: “flawed event design” is another sign of a poorly design program. If it weren’t poorly designed, the programmer wouldn’t think Thread.Sleep was needed.

    Even with a poorly designed program, there’s more alert-able (i.e. better) ways of blocking a thread. WaitHandle.WaitOne, for example, offers a timeout overload. Adding a timeout blocks your thread for at least that timeout or until the WaitHandle becomes unlocked. You then have the option of unlocking whatever WaitHandle-derived object you’re using to interrupt it and stop blocking earlier.

    Maybe another blog post explaining that in detail is in order.

  13. Yes, flawed event design is poor design, but sometimes it is out of your control to do something about it like the examples with .NET SerialPort and bad hardware drivers in the MSDN.VB.NET thread.

    There are many flaws in SerialPort (and Windows), but at least the problem with reopening a port is easy to handle by means of Sleep. Maybe not a pretty solution, but effective and you can live with that. It is much worse that SerialPort/Windows API/Drivers puts an 8-bit wide buffer on top of the 11-bit UART FIFO and in this way efficiently destroys any possibility for a precise break, 9th bit and error detection. I have just bought a $300 expensive kernel mode driver to handle that issue! Of course this is off topic, but I think that it puts things in perspective! There are much worse things than a harmless power nap now and then 🙂

  14. No it is not as I have described in the MSDN.VB.NET thread! If you don’t block the UI thread, the time you need to ensure that the background thread in SerialPort gets scheduled and can close down is of course MUCH longer because the UI thread has higher priority than background threads. Besides, nobody can estimate the necessary time when you don’t block the UI thread. Is it 2 sec., 5 sec. or maybe 10 sec.?

    It is a nice principle never ever to sleep the UI thread, but sometimes the alternative is much worse! If you call Application.DoEvents() before the Sleep(200) command, the display gets updated and before the user can press the mouse button again, the UI thread is ready, so (s)he don’t notice anything. The alternative is to block all transmissions maybe 2 sec. after the port switch and that may irritate the user and will create an unreliable program. Maybe the time should have been 5 sec.?

  15. Your UI thread should be taking very little CPU, regardless of it’s priority difference to the background thread. Most of the time it sits there doing nothing (well, waiting for messages…)

    DoEvents is a bad design choice too, the messages it pumps can get out of order and it provides a perfect means of deadlocking, especially with a SerialPort object.

    One problem is the time you give you sleep is arbitrary, most of the time the pause you get from Sleep isn’t the same plus what you’re asking for is just a guess too.

    You can design yourself into a corner with pretty much anything; but with regard to timer, I’d be doing serial communications on a background thread and a timer (Forms timer if I’m expecting the UI thread to deal with anything, System.Timers otherwise) first an event to start some logic. You can do what you want with a timer, as with anything else, the rest of your application’s architecture has to support it.

    Using Thread.Sleep is coupled to the fact that the thread using it be an MTA thread and that it not be a foreground thread for it to work. That in itself is not a very cohesive design.

  16. … and when the UI thread receives a message it gets busy or even very busy in case of big graphical jobs etc. In that case, you cannot guarantee how long time is needed to be sure that all background threads gets a chance of running. A simple question to you: “How much time is needed under worst case conditions if you don’t block the UI thread?” If you cannot answer that question, your timer solution will not lead to a reliable design!

    Of course the necessary time if you block the UI thread is also completely undefined, but if we test the system, find a time, which does not cause failure under heavy load conditions, and then add a resonable safety factor – say 10, we are still within resonable times – for example 50 mS x 10 = 500 mS. If the necessary time with the UI thread running is 500 mS and we use the same safety factor, we get 5 sec., which is so long that it may be noticed. That’s the problem! SerialPort needs some time to close down. That’s a fact. So either you Sleep the UI thread for e.g. 500 mS to be resonable sure or you use e.g. a 5 sec. timer. There are simply no other alternatives!

    “DoEvents is a bad design choice too, the messages it pumps can get out of order and it provides a perfect means of deadlocking, especially with a SerialPort object.”

    That’s one of those statements, which really need a better, technical explanation! DoEvents just empty the message queue. How can messages get out of order (except of course for WM_QUIT, WM_PAINT and WM_TIMER, which are always delayed until there are no more messages), how can it lead to deadlock situations and what makes the serial port so special in this case? For your information, I have used similar queue based, event driven, systems for highly demanding electronic process control since 1978, so you better come up with a very logical explanation. I don’t buy everything 😉

  17. “… and when the UI thread receives a message it gets busy or even very busy in case of big graphical jobs etc. In that case, you cannot guarantee how long time is needed to be sure that all background threads gets a chance of running. A simple question to you: “How much time is needed under worst case conditions if you don’t block the UI thread?” If you cannot answer that question, your timer solution will not lead to a reliable design!” What does that have to do with not using the SerialPort for x number of seconds.

    If you don’t need to use the serial port for x number of seconds, it’s easy: start a timer and don’t use the serial port until the timer elapses. Simple as that.

    All the available information about DoEvents is available on the Internet, a comment isn’t an appropriate place to explain that in detail.

  18. I have to agree with Peter 100% on this one. (And I have also been developing extreme realtime industrial/space/milatary systems since the late 1970’s). There simply is NO place for a “Sleep”.

    Phrasing the situation differently, why would you want a timed blocking mechanism which can not (optionally) be terminated early?

    Can you guarentee that in 1,2,3,5 years the program will not evolve so that there is a need to “wake” a blocked thread early?

    Do using WaitOne with a timeout provides equivilant functionallity (i.e. You can guarentee that the thread is blocked for a minimum time) provided you do not code something to explicitly wake it.

    “and when the UI thread receives a message it gets busy or even very busy in case of big graphical jobs etc.”

    Right here I see a major design flaw!

    I do heave graphical applications (e.g. realtime 3D display of ion beam etching gas dispersions) that are combined with realtime industrial control. The UI thread has a “monitor” which is implemented as a timer. The timer is configured to fire every 33mS (30fps), if 66mS (15fps) is exceeded between events an error message is logged.

    This rate is accomplished by performing all graphical calculations in a background thread so that the UI thread simply has to do the rendering (which is actually done by the processor on the graphics card).

    Under certain conditions the calculations them selves (for certain parts of the image) may take significantly longer, but this does NOT effect the UI thread.

    I have been using this architecture since the early 1990’s (originally in C, then C++, now C#) and it has proven quite reliable.

  19. This may have been covered already, but what about threaded methods that read/write to the file system? Here at Pixsy, all of our caught exceptions are forked off into a new thread and recorded to and XML file. However, if two exceptions are thrown at the same time, it is impossible without Sleep()ing to perform this write. The best solution is probably to set up a Windows Service and transfer the exception using Remoting to that service. When the service detects a concurrent file operation to the XML log, it can then reattempt to log the exception until it is logged. This poses a problem, although. In order to reattempt when the XML file is free, trying to write to the file must and catching an exception must be used as logic flow–which should never be done. Have any thoughts?

  20. I’d have to see the code; but Windows doesn’t limit writing to the file system in the same process like it does across processes. Windows won’t let multiple applications physically write to a file at the same time, it synchronizes that access. This is because more than one process uses more than one thread; and it doesn’t make sense to write to a file from more than one thread at a time. Since Windows 3.x functions have not limited a single process writing to a file. This is because 3.x was preemptive. Two threads couldn’t physically be running at the same time, so there was never a problem. This backward compatibility was kept so old programs wouldn’t break…

    Again, I’d have to see the code, but essentially what’s probably happening is you’ve added calls to Thread.Sleep() with increasing timeout values until your program worked. This should be the first sign something’s wrong. You’ve tested it with a particular scenario and haven’t taken into account slower devices (try doing the same thing to a network share over a busy 10Mb network connection to an overloaded server, or to a floppy drive). Essentially what is happening is probably you’ve simply made writing to the file synchronous; making one thread sleep for a long enough period of time until the other thread has completed it’s task (and usually longer…). This is a waste of threads.

  21. I am currently using Thread.Sleep to get past ‘delayed write errors’ when backing up a large amount of data to an external storage device in XP. It is a klooge, but I cannot figure out how to make the OS copy files without caching and eventually failing (I turned of caching in both source and destination drives and tried a lot of fixes suggested on forums, to no avail).

  22. Thread.Sleep(0) is useful for playing nice with other application. If a thread is cpu-bounded on a single processor, say doing something in a tight for-loop, Thread.Sleep(0) will allow other applications, like Internet Explorer, to be more responsive and not as sluggish when not using Thread.Sleep(0).

  23. Tried it. Using Thread.Sleep(1) drops the CPU usage down to 3%, Thread.Sleep(0) offers near 100% usage while still allowing IE to be snappy. Without the Thread.Sleep call at all IE is sluggish.

  24. WIndows Service, timeing is not crtical.

    needs to be running and do something “about every xxx time periods”
    so it needs to “sleep” most of the time.

    what would you recomend ??
    While( Not Exit Status){
    DoWOrk();
    SleepABout(20 seconds);
    }
    ??

  25. Hi,
    I am using thread.sleep in a mail sending function. After sending one mail this has to be stopped for at least 2 seconds (Server does not allow multiple mail sending at a session). And my program is successfull using this technique. Is there any alternative?

  26. I think you’re wrong. Not to say there aren’t plenty of example out there of bad use of Sleep, but this also doesn’t mean there aren’t plenty of good uses for it.

    One example is trying to copy a file across the network as part of a large multi-file copy. We all know that networks get temporary glitches and can fail file copies but they then suceeed moments later. A retry with a delay between each is a perfect use for Sleep — if you think there’s a far superior alternative I’d love to hear it.

    Use also mentioned in a comment above that you prefer Sleep(1) to Sleep(0) for being nice to other processes while running a CPU intensive app. Sleep(1) instead of Sleep(0) here does EXACTLY what you’ve been saying was a misuse of Sleep in the main post — you are guaranteeing that you’ll give up at least 1ms (3 million processor cycles!!!) when nothing else may even want the CPU. Sleep(0) here means “hey, if anyone is starved for CPU time, here take a quick slice, but if not I’d be happy to keep crunching away”.

  27. @I Like Sleep: As with any advice, you have to understand and accept it. I wouldn’t expect anyone to simply do anything I say without thinking about it and understanding it. If you find that after what I said and your experiences and research you don’t agree, that’s great.

    But, I don’t agree what you’ve said is good design. With regard to waiting for retry, where do you do this sleep? If you do it on the UI thread, you’re making your UI non-responsive: very bad. If you’re starting up a new thread, how are you communicating back to the UI thread to retry? If it’s not the UI thread, what is it. If it’s a retry, how are you informing the user and providing the ability to abort the upcoming retry? In the case of aborting the retry or exiting the application with a sleep in the background thread, you can’t–you’d have to abandon the thread and start another if you wanted to offer the ability to perform the retry-able operation to the user, wasting 300,000 cycles to create a new thread and it eventually terminating. Not giving up 300,000 cycles like what Sleep(x) does, but wasting them. If you used a thread-pool thread for this and the thread pool had no more active threads your thread wouldn’t run for 1 second–which usually results in “random” defect reports from your uses. You can’t abort the sleep without either resulting to bad practices or really obscure techniques. With a delay between retries, you have to a) inform the user that you’re going to retry, b) provide the ability to abort the upcoming retry, and c) not stop the application from exiting (i.e. if you have a non-background thread running int the background stuck on Sleep, the application won’t exit from memory until the Sleep returns or some pre-defined amount of time when the CLR gives up on the thread. To support these cases I would recommend a timer. When the timer elapses initiate a retry. If the user wants to abort, you simply reset the timer; if they want to exit the app, it’s the same thing.

    Thread.Sleep() is implemented by calling the native SleepEx. Read the documentation for SleepEx (I’ve added it to the .NET 2.0 Thread.Sleep documentation as community content) SleepEx(0) relinquishes control to other threads “of equal priority that is ready to run”. This means you’re *not* relinquishing control to anyone starved for CPU (i.e. you’re not relinquishing control to a lower- or higher-priority thread) which can lead to starvation and race conditions. Plus, use of Sleep(0) can actually use up more CPU cycles that Sleep(1) because the OS has to eventually get involved because of the priority issue. Besides, you’re relinquishing control, that means you’re giving up your timeslice. Saying that is the same as what I’m complaining about is pedantic, 1ms isn’t going to give the application the appearance of not being exitable. Use of Sleep(1) over Sleep(0) can actually make an application consistently appear more responsive and use less CPU.

    See also http://www.bluebytesoftware.com/blog/PermaLink,guid,1c013d42-c983-4102-9233-ca54b8f3d1a1.aspx and the rest of Joe Duffy’s blog.

  28. I have no UI. I’m a webservice. If your advice is never to call Sleep on a UI thread, or a thread running a message pump, I can agree with that. I just can’t agree with “Thread.Sleep is sign of a poorly designed program”.

  29. I find Sleep is very useful in following case. -> Ur application run in the back ground say as a window service.

    -> U have a strict requirement that asks ur application not to use more than x% of CPU.

    Do you find any other way than Sleep which will release the CPU for other and guarantees that ur application never uses more than x% CPU as specified.

    Please comment…

  30. @Sumit: Sleep means that the current thread has been reserved for ~x number of milliseconds. Does that mean CPU usage is throttled? Yes. Does it reliably allow you to throttle CPU usage to a given %? No, Sleep isn’t that accurate; it may sleep for less time, it may sleep for more time. But, it also means you now cannot do anything else with that thread until the time has expired. This also means anything dependant on that thread is not dependant on that amount of time. E.g. creating a non-background thread that sleeps for 1000 ms means the application cannot exit until Sleep returns.

    You can do the same thing with EventWaitHandles, Mutexs, and have the ability to abort the wait.

    If you’re looking at throttling CPU usage to a specific percent then you should be looking at a managing your own work items and schedule them appropriately. Arbitrarily pausing a thread also means that whatever resources that thread has locked stay locked. E.g. that thread may be writing to a file; if you pause that thread in the middle of that write nothing else can write to that file–you then have a dead-lock. If the thread hasn’t written all the data to the file and what is has written isn’t complete (e.g. you updated the date 01 31 2008 in a file, but only wrote out 02 (feb), you now have an invalid file (02 31 2008 is an invalid date).

  31. Thanx Peter for the valuable comments….

    Yes managing work items for throttling CPU usage to a specific percent is great idea. Can u please explain more in that terms (may be one more blog).

    In the mean while can u pls comment on the flaws on the following design as u find.

    I have a background thread which runs on an infinite loop in following manner ..

    while(true)
    {
    // Acquire necessary lock/resource
    // Perform one well defined task
    // Release lock / resource

    Thread.Sleep(configurable_Time);
    // Just to give CPU to others so that
    // current process does not use more than specific (rough number) % of CPU

    }

  32. I primarily write websites using ASP.Net (C#). Recently I have come across the need to write a windows service that polls a SQL Server Table and does something based on the table values. If the process is running then I do not want to polls the SQL Server table until the process is complete. Base on examples of logic I have found pertaining to creating this service, I was lead here. My problem is that everything I have found so far suggests using Thread.Sleep to accomplish my goal. If this is a bad design what would be a good design for periodically polling a SQL Server table and pausing the polling to do something with the data when the appropriate values are found?

  33. Everything you’ve found so far suggests using Thread.Sleep? Scary.

    If you want to periodically perform some logic I recommend using a System.Timers.Timer object. The System.Timers.Timer.Elapsed event handler would be the place to put the code to query the table. You can pause the timer while you’re doing your processing with the System.Timers.Timer.Enabled property. Alternatively you could use System.Timers.Timer.Stop to pause the timer and System.Timers.Timer.Start to restart it (you’re intentions are a little more clear using Stop/Start).

  34. I am designing a program which has to reliably communicate with an Opto22 PAC on a rack.

    The old regime made use of Thread.Sleep() to force the program to wait some time before checking to see if there was a message in the bytes received back from the Opto.

    Trying to divorce myself of this method, I naively thought I would make a synchronizer class which essentially is a System.Timers.Timer which will count at a certain sampleRate for a certain duration.

    Using a 1000 ms duration, I noticed that for higher sampleRates (~100-1000 ms), the delay is close enough to a second. For 1 ms sampleRates though, it takes over 10 seconds.

    Essentially, my question is whether there is a way to reliably pause for definate amounts of time or whether my communications design is inherently flawed if it relies on such pauses to keep things syncrhonized?

    Thanks for all the help,
    – Dan

  35. You are both right and wrong. I agree and disagree. You should never use thread sleep for timing a thread or an application in Windows. [It is a different matter you can still use delay(n) in DOS, and that works perfectly too, but DOS is not a multi tasking OS]. I have been writing applications that need real time hardware interfacing in C, Turbo Pascal, VC++ and Delphi. In Windows, there is nothing else available for a thread to wait, anything else actually slows down systems. Also, do not forget the fact that all non multi threaded windows applications WITH AN EVENT DRIVEN UI use an infinite loop with a sleep – awake – check if something happened/needs to happen sequence. A straight Windows UI application (maybe in VB or Delphi) sleeps and awakes around 18 times a second to see if a user pressed something or some action has to take place. This is the same across all OSes, and it is nothing new. .NET is known to be thread heavy – especially kernel round trips and mutexes. I do not know whether this is true, but I have heard people say that .NET automatically enforces mutexes in the background without developers being aware of it if there are two or more threads (accessing a common variable) and a DLL assembly in the program, even if only one thread is “writing” to the variable and the others are only “reading” from it. I have been told this happens whenever there is a DLL present, but not on other occasions. I have also been told it becomes very difficult to write proper device drivers using C# and .NET, and that is one of the main reasons for Vista’s unpopularity – device drivers not working for a variety of printers and other hardware devices as they were written using C# and .NET. I do see that C# is a nice language and we are starting a multi threaded hardware interfacing project in C# and there are DLLs too. This project has only one thread updating some common variables and other threads reading from it. The prototype in Delphi works fine, and I am sure that VC++ will also work the way we intend it to. It is .NET which is the unknown here, especially when people tell me that it enforces mutexes in the background without us being aware of it. I am just hoping and praying it is not true. I do like C# as a language, but I don’t want .NET coming in the way.

  36. There are lots of ways in Windows to get a thread to wait that doesn’t affect performance. Most of them deal with thread synchronization. And that’s what you’re effectively doing when you think you need to use Sleep(). What you want is to block the thread until something else happens, it’s just most people only see the time-out part of that “something else” when they should also see that they need to be able to unblock that thread at any time for it to terminate.

    For example, an alternative to Sleep:
    static void ThreadEntry(object parameter)
    {
    EventWaitHandle eventWaitHandle = parameter as EventWaitHandle;
    if (eventWaitHandle == null) return;
    if (false == eventWaitHandle.WaitOne(1000))
    {
    Trace.WriteLine(“doing something in background thread”);
    // do something every second
    }
    // another thread signaled eventWaitHandle
    // effectively asking the thread to exit
    Trace.WriteLine(“exiting thread”);
    }

    I don’t know where you got your other misinformation; but, .NET does not enforce mutexes in the background to synchronize common variables, it’s not difficult to write drivers in C#/.NET–it’s currently impossible,

  37. Jeff, do you have multiple threads polling the SQL table or just one thread?

    I came across a problem in Thread.Sleep that if all threads becomes sequesntial instead of Parallel.

  38. Well I stumbled upon this blogentry while discovering some not so nice timing issues in my application. The problem I have:
    I have an application which monitors the serial port for communication using ReadFile() and a timeout of 75ms, everytime ReadFile() succeeds or times out a message is sent to registered eventlisteners (like a gui or console app which prints the data).
    If I want to send something to an attached modem, I have to precisely set the RTS line, the driver functions like RTS_CONTROL_TOGGLE don’t work good enough, they set RTS to early and clear it way to slow.
    In my first simple application I just used Sleep() and it worked fine (single threaded).
    Basically this is what I need to do:
    [code]
    EscapeCommFunction(hComm,SETRTS);
    Sleep(3);
    // send (Write) it
    WriteFile(hComm,data,datasize,&byteswritten,&osWrite);

    // disable RTS
    Sleep(20);
    EscapeCommFunction(hComm,CLRRTS);
    [/code]
    Now with my enhanced application and the listening thread, I’ve got following problem:
    Sleep(3) gives up the timeslice of the thread and gives the listening thread the chance to do something, which is basically block until timeout which takes 75 ms + some more time.
    Same goes for Sleep(20).
    (in fact I have a method to sleep for microseconds but it still uses Sleep())

    How can I wait for 3 ms (better 2,5 ms) without using Sleep() and without using 100% of my CPU to do nothing?

    Note that I am not using .NET but Visual C++.

  39. @Arsenal. You can’t do it with procedural code (i.e. dosomething, wait, dosomethingelse…) because there’s nothing that has an accurate delay in that model.

    You’d have to use some sort of eventing model. I would suggest having an event for each action you need to perform after a delay, then use a multimedia timer (http://msdn.microsoft.com/en-us/library/ms712713(VS.85).aspx) to fire an “event” (call a callback) after some time delay or use a Timer Queue to call a callback at a specific time.

    Now this is an asynchronous model, which is drastically different than the procedural model; so it will be difficult to design if you’ve never done it before.

  40. To detect if the thread is interrupted simply catch the ThreadInterruptedException. .NET is different than Java, there are no checked exceptions in .NET. In Java, with checked exceptions, each exception that could be thrown during the execution of a method needs to be defined. Since a thread can be interrupted at any point that would mean each and every method needs to document the ThreadInterruptedException.

    I don’t think Sleep(0) in Java truely detects if a thread is interrupted. See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6213203

  41. Peter, thanks for your quick response. I think you misunderstood my post:

    1. In Java, I don’t need to sleep(0) I call the build in method Thread.isInterrupted: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#isInterrupted()

    2. I know about the ThreadInterruptedException, that’s exactly what I used to implement the IsCurrentThreadInterrupted method with the help of Sleep(0) if you follow the link I posted earlier. BUT, the exception is only thrown when the thread is in waiting state. If my thread is executing a long running calculation (this can be simulated with the SpinWait) I will NOT get the exception when the thread is being interrupted. I need a way to detect this and stop my calculation.

    3. I completely agree with you on the use of Sleep(), actually my workaround can cause unnecessary context switch but I don’t seem to be able to find a better way in the .Net world.

  42. In most cases there are better suited alternatives to Thread.Sleep as a timing and in other cases there should be! But hey it’s .NET many things should be…

    I have faced a problem where the accuracy of timing is not just noncritical but actually undesirable. I want to implement a TimerQueue (heap based – very resource friendly) but there are problems with present timers in .NET huge problems.

    DateTime can be changed, TickCount wraps around, StopWatch uses a generally unreliable counter which actually works like wonder in some cases only not a general solution. Thread.Timer is poorly documented, could be good or not I can’t decide based on information available.

    So how exactly would you time?? I need roughly half a second accuracy, in extreme cases it can be a few seconds, but I want my app to be able to run for a very very long time not just 49 or 25 days. I also want simple and elegant solution that works well in optimal situations and simply just works otherwise.

  43. If you need accurate timing you should use the multimedia timers. Even still, Windows is not a realtime operating system so accurate timing is very hard to obtain consistently.

  44. Like I said I don’t need accuracy only a 100% (or close) reliability and a long term rough, statistical accuracy.

    I have recently found a complaint about Threading.Timer suffering also (like I suspected) on 32 bit machines from 49 days nightmare… It’s working exactly like what I wanted to write by the way, only they didn’t worked around the wraparound or so it seems…

    It’s always good practice to use built in solutions to problems, so I might document it as a known bug (introduced by dear MS).

    Or I might use my own 64 bit counter with Thread.Sleep() which is immune to my knowledge of all symptoms above. Ugly I know. Just so simple and simple is good. I will just not say anything about time. Let’s call a cycle heartbeat let’s say a heartbeat is at least 100ms and let’s count ’em! Oh but hey ‘Thread.Sleep is a sign of a poorly designed program’ or poorly designed operating system and framework?

  45. @Lee if it were me, I’d use System.Threading.Timer if the with a failed status to simply retry calling Send after every x seconds.

  46. I can’t use anything native it would defeat the purpose of my project. Bad enough that native limitations present themselves so crudely in .NET…

    Every timer that uses current time as a basis is susceptible to user or automated date-time updates messing up any timing. Unless the OS updates waitable timers on every adjustment… DOES IT?

    It’s clear that some kind of nonadjustable counter is needed for such timings like the hardware performance counter or worst case the TickCount which is interrupt driven.

    SetTimer() could have been written to work properly since there is an USER_TIMER_MAXIMUM with the value of 0x7fffffff given this one could actually handle a wraparound, I could even write the C code for it, but DID THEY?

    As far as I can see from posts and writings on the net there are reliability problems with every one currently available timer. Which is insane given that it’s a very very basic and common task.

  47. @deman: If you use System.Timers or Threading.Timers, those end up being native too. It doesn’t defeat the purpose, it only gets into permission issues with assemblies that call native APIs (the .NET Framework assemblies have native permissions by default).

    The timers are meant as timers; it’s highly unlikely that a “timer” would need to run pass 49 days, which is why it doesn’t support an infinite amount of time.

    Beyond 49 days (well, beyond a day; but that’s beside the point) you’re really looking at scheduling actions to run, not a timer. There’s libraries like Quartz.NET (http://quartznet.sourceforge.net/) for scheduling tasks.

    So, the only other option with a timer is to chain timers. Set a timer for the maximum value (49+days, depending on the timer, and when that expires/elapses, start another timer–keep doing that until the final amount of time has elapsed.

  48. I commonly use Thread.Sleep for tasks like this: I call (e.g.) Socket.Connect, but it fails because the Server is not running yet, so I have to retry connecting until the server is up. If I retry connecting right away, my connect thread will under certain conditions use 100% CPU. To prevent this, I simply call Thread.Sleep(10) after each failed attempt to connect to the server.

  49. @Niki: Using Thread.Sleep(1) will relinquish the CPU to another waiting thread; which is an acceptable use of Sleep. What happens with Sleep(10) is that it’s lower than the thread quantum (which is 100-200 ms, depending on the type of the OS), which really ends up being Sleep(1).

  50. Back in the day when i played Everquest, that particular game had poor coding and it was very unresponsive especially if you were playing multiple accounts on the same computer and wanted to Alt-Tab between the different game instances..

    As an example when you had one of your characters auto-following the other character, the character whose gameprocess did not have window focus, would fall behind because it didnt get enough time-slices to actually do all the processing it needed to do to (literally) keep up when you were running around with your characters.

    Fortunatly it was possible by code injection to hook into the process and a simple Sleep(0) injected into the end of the game loop of each process made a huge difference in playability.

    Suddenly it was possible to play multiple characters on the same computer, because now the available CPU ressources got distributed equally and in a fair manner between all game instances.

    I’m not even sure who I blame the need for this hack on, the Everquest programmers, or the guys who wrote the windows scheduler..

    I’m actually tending towards the latter.

    But at least this is one case where Sleep(0) actually made a huge difference(the difference between being able to control 4 characters on one computer as opposed to max 2)

  51. @bo. The fact that it functions better with a call to Sleep(0) means it wasn’t designed properly. Sleep(0) (while not as flawed as Sleep(x)) is like goto…

  52. Back in 2003 we ported a massive Windows application to ASP.NET. The application has 200 Crystal reports with user selectable parameters (facilities, areas, items, date range, etc…) so that each report may take up to several minutes to run depending on the report, the data, and the parameters selected. Each customer has their own copy of the database. We store Session State in SQL Server, which includes the datasets for the reports. As we migrated more customers to the web app we ran into a problem in late 2007 where SQL Server would cause the CPU to hit 100% and the application would become unresponsive. As a quick workaround solution we added a Sleep(1) to our library function that executes each query. Some reports execute a few queries while others may execute thousands. This temporarily solved the problem but of course had the negative side affect of slowing the reports down. As we continued to add customers to the site we had to eventually bump up to Sleep(5) over the course of two months. We spent weeks performance tuning a number of slow running reports and have not had any problems for the past year even though we now have thousands of users. We tried lowering the Sleep last summer but the 100% CPU problem came back again. What would you suggest I do to eliminate the sleep so that the reports run faster but without SQL Server maxing out the CPU?

  53. @Dave: The reason you see a difference between Sleep(1) and Sleep(5) (or anything below Sleep(100) is that the amount of time you give to Sleep is a recommendation, the system causes that thread to relinquish control of the the processor for a number of timeslices that fit within the requested delay time. Time slices are 100-200 ms (depending on the version of Windows) and therefore anything above 1 would effectively be 100/200.

    1 and 0 have special meaning. 0 means relinquish control only if another thread of equal priority (not equal and greater) is waiting and 1 means only relinquish control if any other thread that is waiting. Sleep(0) is not recommended because it doesn’t do what you expect–you should always use Sleep(1) to relinquish control to other threads.

    Sleep(1) is a generally acceptable means of relinquishing control to other threads; but it’s generally better to design it so it doesn’t hog the CPU.

    In your case, if and I were fixing it, I would move towards using a scheduling system where there is no “waiting” required–i.e. the scheduler (like Quartz.NET) is responsible for queueing up the reports to run). But, it’s hard to recommend something specific without more thorough knowledge of the solution.

    I really need another post that details Sleep(0) and Sleep(1)…

  54. I use thread-sleep to slow-down my CPU/IO intensive non-critical background tasks apps (on a server) to make it more resource friendly.

    IS that a bad design?

  55. @Andy. I think it’s a bad design because you’re committing your thread for a specific amount of time, it can’t be interrupted and you can’t safely stop it until it stops sleeping.

  56. I wrote my post not in order to get information on the Sleep method but in the hopes to find a solution to the high CPU% that would allow me to eliminate the Sleep. I searched to find out how to acquire the CPU%, much like is shown in Task Manager, and came across the following MSDN page:

    http://msdn.microsoft.com/en-us/library/system.diagnostics.performancecounter.aspx

    What are your thoughts on examples on the page which use the Sleep method, especially the CPUUsage class in the community comment section?

  57. I know I’m not as smart as the author or the posters here, but I use Thread.Sleep all the time.

    I write software for realtime systems. I’m continually polling I/O and running state machines. If I do NOT use the sleep command when polling (and this goes for all the threads in the application – could be anywhere from 2 to 15), CPU usage goes up over 90%. If I sleep for 100 ms, it goes back close to zero.

    I usually have other applications running on the system as well and I don’t want to hang them up. What other method exists to run realtime loops without penalizing other applications on the same machine?

  58. Just as a foolowup –

    Many of my tasks don’t have to do anything for roughly 5 seconds. I use tickcount to measure that time in ms. But I don’t need to be looking at that tick count every cycle. If the task works in 4.95 seconds as opposed to 5.001, I really don’t care. If it takes slightly longer, I really don’t care either. So, if I sleep for 100 ms before looking st tick counts, I have one line of code for someone else to follow that gets my CPU usage back down to normal.

    Obviously, I could put a bunch of code in there to basically accomplish the same thing to make thread behave in a way YOU seem to need – not me.

    So, my point is, you’ve painted with a pretty broad brush here and I just don’t think your argument holds water in every case. I beleive that the sleep command DOES have a place in non-critical timing threads. Part of my job is not just getting systems to work, it’s also making it easy for someone else to take over the code.

    I’ve been writing realtime systems for a lot of years, and not once – ever – has the sleep command come back to bite me. Sometimes we don’t need a sledgehammer when a tack hammer will do. It’s not poor design – it’s simplicity.

  59. I wrote a version of CPUUsage to acquire the CPU% using a timer. Is this what you mean by a good example of “Sleepless” coding?

    Public Class Form1
    Dim CPU_Percentage As New CPUUsage
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
    TextBox1.Text = CPU_Percentage.GetCurrentCPUActivity & “%”
    End Sub
    End Class
    Public Class CPUUsage
    Private ReadOnly PCPUUsage As PerformanceCounter
    Public Sub New()
    PCPUUsage = New PerformanceCounter
    PCPUUsage.CategoryName = “Processor”
    PCPUUsage.CounterName = “% Processor Time”
    PCPUUsage.InstanceName = “_Total”
    PCPUUsage.NextValue()
    End Sub
    Public Function GetCurrentCPUActivity() As Integer
    Return PCPUUsage.NextValue()
    End Function
    End Class

  60. Wow, this is a really hot topic. I must admit to not fully understanding all the intricacies of STA and MTA threads, but the discussion itself is quite enthralling. Thanks for taking the time to explain it in such detail. Now just to wrap it around my brain, lol.

  61. We are looking for a way to relinquish CPU cycles to other applications in a milti-threaded application. If we use sleep.thread(1) in each thread then my assumption is that our other threads will take the CPU.

    The question is…how can we use thread.sleep(1) on all of our threads simultaneously so that CPU cycles are open for other applications?

  62. @Richard. Right, using Thread.Sleep(1) will allow any other thread to take control of the CPU for at least a time-slice.

    The question is a little misguided. The parameter to Sleep is the number of milliseconds to sleep. The fact that we’re using 1 millisecond as a parameter means it’s *really* difficult for any number of threads to be calling Thread.Sleep at the very same time. Then, there’s the fact that only one thread at a time per processor is actually running…

    Your question suggests to me that you want to dip into thread prioritization. You want to periodically do no work so other applications can do some. But, you don’t know what those other applications do or whether stopping your work will benefit them at all. I wouldn’t suggest writing your application to do this; there’s no way to do it correctly without being the operating system. Using Thread.Sleep(1) in your threads is enough for the operating system to allow other threads to be responsive. It works remarkably well.

    Are you using Thread.Sleep(1) and seeing that other applications are being starved of CPU?

  63. Thanks for the tip, I didn’t know that.

    In fact, the MSDN doc about the Sleep method is pretty unfair :

    “The number of milliseconds for which the thread is blocked.”

    So from now I will use the System.Threading.Timer class instead…

  64. I use Thread.Sleep with the .Net ThreadPool in a c++ CLI winform app. I don’t have the luxury of the console so a textbox created from the main UI to simulate console I/O on separate threads is the only alternative I can see.
    The threadpool does a great job of keeping tabs on the threads created. Of course I have to Invoke a delegate to communicate with the textbox as well. There is the nasty Exception of cross threading if I don’t use seperate threads and a delegate.
    Anyone have a better idea. I’m all ears.
    Thanks

  65. I use Thread.Sleep on occasion to reduce processor load and thus power drain on mobile devices in heavy message loop based systems. Im currently using it in a iPhone UI for windows mobile where I have a main application thread setup that is similar to the message loop that handles windows applications. I use a 5 milliseccond sleep just to ensure that im not bombarding the CPU with GOTO and Compare statements between invalidate and mouse messages from the while loop, Without the Sleep it works fine but the device gets hot and drains battery faster than it can charge.

  66. I read this whole post, a feat in itself. It appears to me that you are saying “using Threading.Sleep() is a bad idea”. You are also saying “In many cases where an engineer is tempted to use Sleep() to facilitate timing or resource management, there is probably a better way to do it, if the engineer in question has enough control over the system components to rearchitect the approach.”

    It seems you have noted that there are times when doing something *like* a Sleep() is a reasonable approach, especially when an engineer DOES NOT have control over related system components and must work around their behaviour, whatever that may be. In some says saying it is a sign of a poorly designed system doesn’t matter much in some practical circumstances where some important system that has cost years and millions to produce has to be utilized and worked around, not recreated and made “right”. So obviously, there ARE some cases where a Sleep() *like* operation may be inevitable even against preference. But even in those cases, much of the time at least an interruptable wait such as WaitOne() should be employed so the Sleep does not totally relinquish control of the thread in the process (unless you also are willing to abort the thread… you aren’t right?).

    I would suggest a better tactic to communicate this information, instead of simply saying “sleep is bad”, would be to briefly point out the flaws and pitfalls of sleep, and then go on to point out how to implement the various design patters using a mechanism that is equivalent but avoids the pitfalls. In this way you are not arguing semantics – but syntax, since in the end each design pattern is valid as an idea and however the language makes available a reliable mechanism to implement the pattern is worth discussing.

    The issue is that Sleep() is used to implement designs where it is in fact a poorer fit for those designs than other solutions.

    For example, can you control the whole system? Consider using an event driven pattern where your system components can notify each other of changes, instead of watching and waiting on each other.

    If you can’t control the whole system, and must revert to a polling mechanism to get data from some component which operates outside your control, you can employ a timer or possibly a wait.

    If you just want to tell the OS you are not very important and it can schedule someone else right now? Ok, MAYBE Sleep(1) is an option, according to the author.

    In most of these cases, Sleep() can be made to ‘work’ some percentage of the time, but is arguably not the best or most elegant solution available in C#.

    However, as some developers have noted, sometimes we end up porting or integrating code from one platform to another, and some facility in that one platform may not appear in the other. Sometimes we can rewrite the whole approach, but sometimes we can’t. Sometimes there are millions of lines of code that implicitly depend on the missing facility, and it makes more sense to simulate it in 1 day’s coding rather than spend 10 years ‘fixing the design’. If you have looked everywhere and asked every question and it seems like using Sleep() ends up being the only known way to cross that bridge… go for it IMO. The point is, in the real world, we have to consider all our options, and pick the best one for the CIRCUMSTANCE. This is an art to be sure. And a dangerous one at that. So just take this ‘bad design’ hoopla with a grain of salt. I think the point is, yes it is generally a bad design, yes it has flaws and pitfalls and you should look at the alternatives. In most cases there is a better option.

    I think that is the author’s point.

  67. I have a .NET-application serving as UI-front-end for a legacy Win32-application. The Win32 app was changed so I can run it as a DLL. The Win32 app is run on a separate thread.

    The UI front-end dispatches to the Win32-thread when the user uses the .NET-UI to select commands. If the Win32 app needs to change something in the UI, it dispatches to the .NET-UI-thread.

    Now I need to cleanly shut down the application when it exits. I do this by responding to the .NET Application.Exit event. In my handler (which runs on the .NET-UI-thread), if the Win32-thread has not yet completed, I send a command to the Win32 app to shut down. Now I have to wait until the Win32-thread is done before exiting the handler-method. As part of the Win32-shutdown process, the Win32-thread also dispatches some things to the .NET-UI-thread. So a simple Thread.Join() doesn’t work.

    Currently I do it as follows. If you see a better way, please tell me:

    while (win32thread.IsAlive)
    {
    // Relinquish control
    Thread.Sleep(1);

    // Empty the dispatcher-queue
    Application.DoEvents();
    }

  68. I think the intention for Peter’s post was thread.sleep shouldnt be the first option to use when faced with a thread timing issue, however the title is “Thread.Sleep is a sign of a poorly designed program” and when you search for “thread sleep vb.net” on google this is the first page that comes up, and it appears a little offensive to anyone who relies on it for an innocent issue and has no need for utmost cpu efficiency or the utmost precise timing.

    I have another one where i absolutely need it as far as ive tested. It involves printing a report automatically in vb.net from a connecting client posting invoice data via multithreaded net sockets, to a written csv for keepsake, then an mdb for the reports sake using an sql query which is a work around in its own right. I have duplicate code and the one which goes through this multithreading stuff and not the normal gui thread needs a thread.sleep of no less than 500ms(~) or the report is empty.

  69. Hi Peter,

    I am intrigued by your article. Perhaps you could advise me on how to remove thread.sleep from one of my programs.

    I have sixteen identical devices that need to be interacted with at the same time, so sixteen threads are used.
    I send a command, and know it will take no more than three seconds for the devices to complete the action. So, in each thread, I thread.sleep for three seconds before the executing the next command.
    The devices are mechanical; there is no feed back.
    If not thread.sleep, how should I wait the three seconds?

    Thanks

  70. What would be a good alternative to this code?

    I’m a beginner so I’m not good with this threading stuff. I used thread.sleep to poll data from a gprs modem. I set it to a fixed amount of time so that I can ensure all the data goes through. I am ok with not using sleep if only I need to send 1 SMS at a time, since its more of a “fire and forget” if its just one. the problem is that if I have to send multiple SMS. The modem would return an error if it hasn’t given enough time to process a message. By the way, this is running in a separate thread and so far, has not been consuming my CPU.

    string portdata = “”;
    port.WriteLine(“AT+CMGF = 1\r”);
    Thread.Sleep(100);
    port.WriteLine(“AT+CMGS=\”” + number + “\”\r”);
    Thread.Sleep(200);
    port.WriteLine(message + (char)26);
    Thread.Sleep(1000);
    while (port.BytesToRead > 0)
    {
    portdata += port.ReadExisting();
    Thread.Sleep(4500);
    }

  71. Would you frown upon using Thread.Sleep in the following circumstances?

    Running a multi threaded application that sends data record by record from a batch file to a server and awaits a response for each record. The multi threads are used to utilize mulitiple processors on the remote server. And the number of records being processing is over 1 million. 1 million requests to the remote server. Without slowing down my application by say, 100 milliseconds per thread, my server’s resources and CPU quickly get bogged down and grind to a halt as the threads pile up awaiting responses from the remote server. So, in effect I am slowing down my server to wait for the remote server to catch up.

    I see no problem with this approach. I’ve got a couple of applications where I need to add a stratagically placed timer.sleep and it makes all the difference and works flawlessly.

    Not all of us are developing applications for NASA. For the many of us who write batch programs that run in a fast paced production environment, you use what you need to use to get an accurate and timely result.

  72. In some of this discussion, the problems with Sleep() are related to the implementation. It is also considered bad design to base one’s design upon an implementation.

  73. its not a sign of a poorly designed program
    everyone has their own purpose of using thread.sleep
    plus, if you don’t know this yet
    we are now in the year 2011
    where we have quad core processors running in x ghz that could do a lot of thread.sleep hands down

  74. Fairly accurate ms sleep() timings without hogging CPU are possible. ~2ms accuracy can be had on a typical PC as verfied with a scope.

  75. I have to partially disagree with the main post. I know there are a lot elegant ways to replace a sleep, but they are not portable. I also agree that “sleep” the UI thread is not a good idea. But there are a lot of examples in which you have to do repetitive and predictable tasks, like a GPS which sends a position every 1 second, which is a text of an unpredictable lenght, and you dont have a “message finished” message, you simply got a bunch of text each 1 second. So polling the port with a sleep(1) is useless. There are a lot of mechanical devices (and servers maybe) which needs to follow a “secuential state” and you know it is impossible that they will respond in less than XXX seconds.If you have a sleep(100), and you close your program, it is not terrible to wait 100 ms for the thread to die. And there is also portability, a “sleep” is present in almost all multithreaded languages. With new CPUs, the error of a thread.sleep is possibly less than 1 – 2 ms, and is only 1 line of code.

  76. @RATAK How is Thread.Sleep() portable? Many other platforms use signals for multi-threading. Must like timers or interrupts they’re invoked based on some conditions and threads don’t have a concept of “sleeping” merely yielding to the next signal.

    Why would you not use a timer if you doing something every 1 second?

    what is “secuential state”? Do you mean “sequential state”? What does that got to do with Sleep()? Many mechanical devices deal with interrupts where sleeping would put the software completely out of sync with the hardware.

    “sleep” isn’t a language feature, it’s a platform or framework feature and not all platforms have a “sleep”.

    Just presenting your opinion that you don’t agree and mentioning various things doesn’t make your position correct…

  77. In “secuential” I meant “sequential” I’m not an english native speaker, so you can expect this kind of mistakes. In many thread “loops” you will need to do things like: 1.- Get data, 2.- Process the data, 3.- wait for the next loop. If we don’t wait, in several platforms, you will get a 100% CPU load for doing something that is only relevant once per second. If you use an accurate timer, something will need to poll that timer, if it’s a scheduling system timer, it’s alright, but perhaps you can enlight us in using that in .NET without affecting portability. For example, if your thread processing task lasts 50uS, and you need to repeat that once a second, why it is so important to keep that thread alive consuming CPU the other 99.99% of the duty cycle?. Perhaps you can provide us an example so we can really understand your point.

  78. Additionally you are right, “sleep” is not present in all platforms, but there are similar commands that do the same: Java uses “Thread.sleep”, Some versions of C++ for embedded platforms use “WaitFor(xxx)” when using cooperative multitasking, but all of them do nearly the same thing, switching the thread off, without using CPU for a certain amount of time.

  79. Multithreading and async callbacks are hard.
    I have a process which checks files – whenever they are updated, lengthy processing occurs. I want to check the files every five seconds, and the processing takes around 1 minute. A loop per file that checks the file, does the processing if required, then sleeps for five seconds is just right. How would a timer improve that design ?

  80. @DW I’m not sure a timer would be the best bet here. Depending on what’s going on, a WaitHandle-derive synchronization primitive might be better.

    If you’re doing something in response to changes, FileSystemWatcher might be a better choice.

  81. When you say “e.g., if Sleep(0) means relinquish the current thread […]”, you meant i.e., since you were clarifying and not giving an example.

  82. 0 down vote

    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 – 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? Only syntax lawyers would, be practical!

  83. @dd I detailed how Thread.Sleep for timing *does not* work–the fact of using it where it can’t work is complicating things.

  84. For those of you who hasn’t seen one valid argument against use of Thread.Sleep in SCENARIO 2, there really is one – application exit be held up by the while loop (SCENARIO 1/3 is just plain stupid so not worthy of more mentioning)

    Many who pretend to be in-the-know, screaming Thread.Sleep is evil failed to mentioned a single valid reason for those of us who demanded a practical reason not to use it – but here it is, thanks to Pete – Thread.Sleep is Evil (can be easily avoided with a timer/handler)

    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(Thread.CurrentThread.ThreadState.ToString() + ” ” + i);

    Thread.Sleep(1000 * 10);
    i++;
    }
    }
    finally
    {
    Console.WriteLine(“Exiting while loop”);
    }
    return;
    }

  85. So, I’m just going to throw gas on this fire. Here’s how I approach a windows service that needs to do stuff and sleep for a few seconds up to [insert favorite time period here]. I don’t see a problem with doing it this way. Am I still “doing it wrong”?

    static bool AllowRun = false;
    static void Main()
    {
    AllowRun = true;
    Thread t = new Thread(new ThreadStart(ThreadFunc));
    t.Start();
    Console.WriteLine(“Hit any key to exit.”);
    Console.ReadLine();
    Console.WriteLine(“App exiting”);
    OnStop();
    return;

    }

    static void OnStop()
    {
    AllowRun = false;
    }

    static void ThreadFunc()
    {
    int i=0;
    try
    {
    while (AllowRun)
    {
    Console.WriteLine(Thread.CurrentThread.ThreadState.ToString() + ” ” + i);
    Thread.Sleep(1000 * 10);
    i++;
    }
    }
    finally
    {
    Console.WriteLine(“Exiting while loop”);
    }
    return;
    }

    The service finishes what it’s doing, “sleeps”, and then drops to the finally (and exists or whatever).

  86. @Brisn Smith

    So, what if the service *can* stop when OnStop is called but it’s stuck in a Thread.Sleep? On shutdown, a service is only allowed a couple of seconds to shutdown, if your process is stuck in Sleep for more than 2 seconds your service can’t shutdown cleanly (if it actually could).

  87. @Peter

    Won’t this also be the case in the context of a Windows Service using Timers? What if I’m in the middle of a loop inside of a Timer.Tick() event and suddenly the windows service wants to shut down. I check for the shutdown event after I’m done processing and change the timer’s due time, but what if my “processing” takes longer than I’m given to shutdown?

    Don’t I have the same problem?

    Or is the solution more atomicity? Do more granular work and check for the ShutDown event more often?

    I’m not trying to just troll. I want to understand this as Thread.Sleep() is how I’ve done services forever and if I’m doing it wrong I want to stop.

  88. Your reference to the FileSystemWatcher class seems to be valid (just like this article) until you go deeper.

    What if the FileSystemWatcher class simply does not provide enough information about the file changes? (It does not say anything about the user who changed the file for instance…)

    What if the FileSystemWatcher class is not accurate enough? (It do fails to trigger the notification event in more than 0.12% of rare- (< 1 sec between file operations) and in more than 18% of frequent (< 300 changes/sec) file operations.) The event-driven effort could be useful if the OS would support to do so, but it does not, however a program that polls the watched files could easily check literally thousands of files more then a hundred times/sec. (I have suffered to solve a problem like that recently.) On the other hand I have to say, your article is only valid from a certain point of view: High-end performance-critical strongly multithreaded software should not use Thread.Sleep, because it is a waste of precious resources and CPU time, which can be preserved for the running task. O.K. but what's with the simple tasks, that has to be performed a dozen times a day, but has to be performed for years? Like check if the spam folder on a mail server reached a predefined limit. Should the service be using processor time and maybe virtual memory checking the tick count (or even a performance counter) two million times per second just to see if a few hours been passed? Or should the scheduler be spammed with such tasks timed for the next few years? (Scheduling one run and rescheduling the next on run would be far from what I call secure.)

  89. And – since the Timer is – probably – a background thread that sleeps the desired amount of milliseconds, then wakes up to send a windows message to my thread which is in a waitable state, not only context switching, but messaging also has to be performed – in what ways would a timer be a more cost-effective solution?

  90. @mg30rg Well, that’s it, a timer *is not* a thread that sleeps–which is why it’s better for periodic tasks. If the timer is a Windows Form timer, it runs on the UI thread so there’s no “context switching”. Other times work in their own threads, if you wanted to do something like communicating to another thread, you’d likely have to “context switch” in some way. But, nothing you’ve described suggests you need to do anything causing a context switch. BTW, A sleeping thread forces a context switch when it re-activates.

  91. If you are talking about a windows timer, you are right in the part, the windows timer is not a thread that sleeps.
    You are wrong in the part you could use one in the case I have mentioned because windows services has no user interface, so the timer component has no target to post a WM_TIMER message. You might hack yourself a window handle, but that will lead to some hardly predictable behavior, which I really would not call a proper code design.

Leave a Reply to PeterRitchie Cancel reply

Your email address will not be published. Required fields are marked *