title: Thread-pool friendly approach to Sleep?
body: <p>I want to insert a sleep (aka throttle, delay, tarpit, dwell) in an ASP.net application (imagine something like failed logon attempt escalating delay).</p>
  
  <pre><code>protected void Page_Load(object sender, EventArgs e)
  {
      Int32 sleepyTime = GetSleepyTime(Request);
  
      if (sleepyTime &gt; 0)
          System.Threading.Thread.Sleep(sleepyTime);
  
  
      //...Continue normal processing
  }
  </code></pre>
  
  <p>I want all remaining processing to continue as normal; i just want the user agent to suffer. </p>
  
  <p>The problem is that ASP.net uses a ThreadPool to handle requests. If i were to <code>Sleep</code> for 5, 10, 30 seconds, i would be eating up a valuable limited resource. </p>
  
  <p>I assume it needs to be something like:</p>
  
  <pre><code>protected void Page_Load(object sender, EventArgs e)
  {
      Int32 sleepyTime = GetSleepyTime(Request);
  
      if (sleepyTime &gt; 0)
         ABetterKindOfSleep(sleepyTime);
  
      //...Continue normal processing
  }
  
  private void ABetterKindOfSleep(int milliseconds)
  {
     await SleepAsync(milliseconds);
  }
  
  private async void SleepAsync(int milliseconds)
  {
     System.Threading.Thread.Sleep(milliseconds);
  }
  </code></pre>
  
  <p>But never having written any async/await code, and not understanding the logic behind where the <code>async</code> and <code>await</code> go, or why, or even if it can be used to run async code: i don't know if it can be used to run async code.</p>
  
  <h2>Bonus Reading</h2>
  
  <ul>
  <li><a href="https://stackoverflow.com/questions/23657709/does-thread-sleep-affect-the-threadpool">Does Thread.Sleep affect the ThreadPool?</a></li>
  <li><a href="https://stackoverflow.com/questions/6305814/sleeping-in-a-pooled-c-sharp-thread">Sleeping in a pooled C# thread</a></li>
  <li><a href="https://stackoverflow.com/questions/761313/how-to-delay-throttle-login-attempts-in-asp-net">How to delay / throttle login attempts in ASP.NET?</a></li>
  <li><a href="https://stackoverflow.com/questions/15924221/asynchronous-thread-sleep">Asynchronous Thread.Sleep()</a></li>
  </ul>