83939

Thread-pool friendly approach to Sleep?

Question:

I want to insert a sleep (aka throttle, delay, tarpit, dwell) in an ASP.net application (imagine something like failed logon attempt escalating delay).

protected void Page_Load(object sender, EventArgs e) { Int32 sleepyTime = GetSleepyTime(Request); if (sleepyTime > 0) System.Threading.Thread.Sleep(sleepyTime); //...Continue normal processing }

I want all remaining processing to continue as normal; i just want the user agent to suffer.

The problem is that ASP.net uses a ThreadPool to handle requests. If i were to Sleep for 5, 10, 30 seconds, i would be eating up a valuable limited resource.

I assume it needs to be something like:

protected void Page_Load(object sender, EventArgs e) { Int32 sleepyTime = GetSleepyTime(Request); if (sleepyTime > 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); }

But never having written any async/await code, and not understanding the logic behind where the async and await 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.

<h2>Bonus Reading</h2> <ul><li><a href="https://stackoverflow.com/questions/23657709/does-thread-sleep-affect-the-threadpool" rel="nofollow">Does Thread.Sleep affect the ThreadPool?</a></li> <li><a href="https://stackoverflow.com/questions/6305814/sleeping-in-a-pooled-c-sharp-thread" rel="nofollow">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" rel="nofollow">How to delay / throttle login attempts in ASP.NET?</a></li> <li><a href="https://stackoverflow.com/questions/15924221/asynchronous-thread-sleep" rel="nofollow">Asynchronous Thread.Sleep()</a></li> </ul>

Answer1:

The async equivalent of Thread.Sleep is await Task.Delay:

if (sleepyTime > 0) await Task.Delay(sleepyTime);

Note that this must be used in the context of an async method, and there are limitations (particularly on WebForms) on where async can be used. For more information, see my <a href="https://msdn.microsoft.com/en-us/magazine/dn802603.aspx" rel="nofollow">article on async ASP.NET</a> and the <a href="http://www.asp.net/web-forms/overview/performance-and-caching/using-asynchronous-methods-in-aspnet-45" rel="nofollow">official tutorial on async WebForms</a>.

Recommend

  • Is the Go HTTP handler goroutine expected to exit immediately in this case?
  • dm-script catch error with “Analyze Particles”
  • How can I have an actor running on one process send a message to another actor running on a separate
  • How to set a thread specific environment variable in Python?
  • Parallel sieve of Eratosthenes - Java Multithreading
  • PHP get selected value of select form
  • Mvc 3 posting content type application/json, action method arguments loose mapping?
  • retrieving data from url in iphone
  • How to apply a custom handlers to only specific folder
  • Google Maps api v3 get start and end coordinates of a street
  • HttpClient: disabling chunked encoding
  • How to get latest version of a artifact on Bintray using JSONP
  • IE11 throwing “SCRIPT1014: invalid character” where all other browsers work
  • Graphics.CopyFromScreen [Web application] + The handle is invalid
  • nonblocking BIO_do_connect blocked when there is no internet connected
  • How can I speed up CURL tasks?
  • How to determine if there are bytes available to be read from boost:asio:serial_port
  • Does it make sense to call System.gc() and Thread.sleep() when working on Bitmaps?
  • Bad request using file_get_contents for PUT request in PHP
  • Unity3D & Android: Difference between “UnityMain” and “main” threads?
  • why do I get the error when installing the gem 'pg'? [duplicate]
  • Seeking advice on Jetty HttpClient Hang
  • FileReader+canvas image loading problem
  • Why value captured by reference in lambda is broken? [duplicate]
  • Spray.io: When (not) to use non-blocking route handling?
  • How would I use PHP exceptions to define a redirect?
  • How to redirect a user to a different server and include HTTP basic authentication credentials?
  • Validaiting emails with Net.Mail MailAddress
  • Symfony2: How to get request parameter
  • Timeout for blocking function call, i.e., how to stop waiting for user input after X seconds?
  • Hibernate gives error error as “Access to DialectResolutionInfo cannot be null when 'hibernate.
  • Windows forms listbox.selecteditem displaying “System.Data.DataRowView” instead of actual value
  • Proper folder structure for lots of source files
  • log4net write single file for each call to log.info
  • Getting error when using KSoap library to consume .NET web services
  • Change div Background jquery
  • How does Linux kernel interrupt the application?
  • UserPrincipal.Current returns apppool on IIS
  • Conditional In-Line CSS for IE and Others?
  • How do I use LINQ to get all the Items that have a particular SubItem?