title: How to delay program for a certain number of milliseconds, or until a key is pressed?
body: <p>I need to delay my program's execution for a specified number of milliseconds, but also want the user to be able to escape the wait when a key is pressed. If no key is pressed the program should wait for the specified number of milliseconds.</p>
  
  <p>I have been using <code>Thread.Sleep</code> to halt the program (which in the context of my program I think is ok as the UI is set to minimise during the execution of the main method).</p>
  
  <p>I have thought about doing something like this:</p>
  
  <pre><code>while(GetAsyncKeyState(System.Windows.Forms.Keys.Escape) == 0 || waitTime &gt; totalWait)
  {
      Thread.Sleep(100);
      waitTime += 100;
  }
  </code></pre>
  
  <p>As <code>Thread.Sleep</code> will wait until <em>at least</em> the time specified before waking the thread up, there will obviously be a large unwanted extra delay as it is scaled up in the while loop.</p>
  
  <p>Is there some sort of method that will sleep for a specified amount of time but only while a condition holds true? Or is the above example above the "correct" way to do it but to use a more accurate Sleep method? If so what method can I use?</p>
  
  <p>Thanks in advance for your help.</p>
  
  <p>Edit ---- Possible Idea...</p>
  
  <pre><code>DateTime timeAtStart = DateTime.Now;
  int maxWaitTime = 15000;
  
  while (true)
  {
      if (GetAsyncKeyState(System.Windows.Forms.Keys.Escape) != 0)
      {
          break;
      }
  
      if ((DateTime.Now - timeAtStart).TotalMilliseconds &gt;= maxWaitTime)
      {
          break;
      }
  }
  </code></pre>
  
  <p>This doesn't use any sort of timer but looks like it could work, any suggestions?</p>
  
  <p>Edit 2: The above works for me and now allows me to break the wait when escape is pressed. I have noticed the delay is more accurate than using <code>Thread.Sleep</code> too!</p>