I’d like to equalize my api responses to 2 seconds per call. Do you think this is the proper way to do it (vb.net code)…
Dim timeToSleep = 2000 – Date.Now.Subtract(start).TotalMilliseconds
”CODE TO EXECUTE HERE…
If timeToSleep > 0 Then Threading.Thread.Sleep(timeToSleep)
Does the Threading.Thread.Sleep function block only this api request? What if someone else hits the api request while the Sleep function is executing?
Is there a better way I should be doing this?
Thanks.
While I can think of this being useful only in a testing scenario (load testing/user acceptance testing) to simulate a natural delay, and that this code would never ever touch production, this will work and your call will be delayed while other calls can run. The question is which thread you are blocking:
If you return a normal object or
HttpResponseMessage, your call will block the ASP.NET’s thread pool which in IIS 7 I think is 1000. Any more requests and your server returns 503 error.If you return a
Task<T>, then you are blocking .NET’s ThreadPool threads – unless you specify a scheduler that uses another thread pool. Number threads in this pool will fluctuate between a min and max that can be set using static methods ofThreadPool.I have a few posts on this subject on my blog.