Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The problems with calling <code>Thread.Sleep</code> are <a href="https://blogs.msmvps.com/peterritchie/2007/04/26/thread-sleep-is-a-sign-of-a-poorly-designed-program/" rel="noreferrer">explained quite succinctly here</a>:</p> <blockquote> <p><code>Thread.Sleep</code> has its use: simulating lengthy operations while testing/debugging on an MTA thread. In .NET there's no other reason to use it.</p> <p><code>Thread.Sleep(n)</code> means block the current thread for at least the number of timeslices (or thread quantums) that can occur within <code>n</code> 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 <code>n</code> milliseconds. The likelihood that your thread will re-awaken exactly after <code>n</code> milliseconds is about as impossible as impossible can be. <strong>So, <code>Thread.Sleep</code> is pointless for timing</strong>.</p> <p>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. <strong>This makes any waiting thread a <em>huge</em> waste.</strong></p> </blockquote> <p>The preferred solution: <a href="http://www.albahari.com/threading/part2.aspx#_Signaling_with_Event_Wait_Handles" rel="noreferrer">WaitHandles</a></p> <p>The most-made-mistake is using <code>Thread.Sleep</code> with a while-construct (<a href="https://stackoverflow.com/a/1676030/57508">demo and answer</a>, <a href="http://www.zvolkov.com/clog/2009/07/10/net-4-0-and-better-ways-to-wait-for-queued-threads-to-complete/" rel="noreferrer">nice blog-entry</a>)</p> <p><em>EDIT:</em><br> I would like to enhance my answer:</p> <blockquote> <p>We have 2 different use-cases: </p> <ol> <li><p>We are waiting because we know a specific timespan when we should continue (use <code>Thread.Sleep</code>, <code>System.Threading.Timer</code> or alikes)</p></li> <li><p>We are waiting because some condition changes some time ... keyword(s) is/are <strong>some time</strong>! if the condition-check is in our code-domain, we should use WaitHandles - otherwise the external component should provide some kind of hooks ... if it doesn't its design is bad! </p></li> </ol> <p>My answer mainly covers use-case 2</p> </blockquote>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload