title: Alternatives to using Thread.Sleep for waiting
body: <p>Firstly I am not asking the same question as <a href="https://stackoverflow.com/questions/5450353/c-sharp-alternative-to-thread-sleep">C# - Alternative to Thread.Sleep?</a>, or <a href="https://stackoverflow.com/questions/9118414/alternative-to-thread-sleep-in-c">Alternative to Thread.Sleep in C#?</a>. I don't think I am using it incorrectly and need a genuine alternative for specific situations.</p>
  
  <p>During a code analysis run I saw a surprising violation coming up: </p>
  
  <blockquote>
    <p>Usage of Thread.Sleep() is a sign of flawed design.</p>
  </blockquote>
  
  <p>This violation leads to <a href="https://blogs.msmvps.com/peterritchie/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program/" rel="noreferrer">Peter Richie's article</a> on why exactly this constitutes bad design.</p>
  
  <p>We all know thread creation is expensive and blocking in threads means contention on the pool. We also know that each thread will allocate a meg of memory so it should have a short lifespan, blocking on the UI is evil, using sleep for timing is unreliable etc etc etc. Which leads me to my point, if you really need to perform a sleep, what should you be using if not Thread.Sleep?</p>
  
  <p>Peter goes on to mention that a zero sleep is the only correct use of Thread.Sleep effectively giving up the thread's timeslice and allowing other threads to process. And then even more scary is that this is only a because of limitations on unmanaged threads and if re-implemented in the CLR will create side effects of using Thread.Sleep in your applications. All the points on common bad usage are, in fact, good examples of bad usage.</p>
  
  <p>I have the following situations in production code that uses Thread.Sleep quite successfully:</p>
  
  <ul>
  <li>Waiting for a file lock to be relinquished by the operating system (catch file lock problems, <strong>wait for a second</strong>, try again, give up after a while).</li>
  <li>Killing a process and waiting for it not to show up in the process list (kill it, check it's not running, <strong>wait for a second</strong>, check it not still running, force it closed).</li>
  <li>Waiting for copy buffers to flush (check a file size, try to access it, <strong>wait</strong>, check if size has changed).</li>
  </ul>
  
  <p>Without using Thread.Sleep in situations like these, what other options do I have? Tight loops tend to make things worse and I don't believe this makes it's usage a "design flaw" especially since nothing is on the UI and only in background threads. It is just the nature of software to wait for other things in a multi-threaded environment with external factors affecting your code, sometimes you need to wait...</p>