I have an ASP.Net MVC 4 application that periodically calls an external API for information (resource). This resource has a rate limiter for the account (meaning other apps use the same pool and may hit the limit). When this limit is hit, It will send back a HTTP Status Code 429 with a header of "Retry-After" in seconds (lets say 25 seconds).
If my app gets this response, I will then need to delay execution for 25 Seconds and retry. First off, let me say that the method that this code is running under is an ASP.Net 4.5 Async method. For this, I was thinking about using the System.Threading.Thread.Sleep(25000)
Now, I really don't like to use this, is there a better way of doing this?
I have to say that I apologize for this open ended question, but I couldn't find anything on the proper way of delay execution (while keeping things async and making sure that we don't run out of threads)
Update: Would the following code be better for the delay?
await Task.Run(() => Thread.Sleep(10000))
You shouldn't use Thread.Sleep
because it blocks the thread for that amount of time so your server is less scalable. You should instead use Task.Delay
which waits asynchronously without blocking a thread:
await Task.Delay(10000)
Task.Delay
uses a Timer
internally to accomplish that. For more info: Thread.Sleep vs Task.Delay?
I recommend you use the Transient Fault Handling Block, which was designed specifically for this kind of scenario.
However, if you want to implement your own retry mechanism, Task.Delay
is a better choice than Task.Run
+Thread.Sleep
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With