How to introduce a delay between webrequests to a site in C#?
-
14-10-2019 - |
Question
I making making multiple requests to a website. How can I introduce a delay between requests to slow down my process? Is there a method that allows me to just cause the thread to just wait for X seconds before proceeding?
Solution
Are you looking for Thread.Sleep
?
Note that it causes the current thread to sleep - you don't target it at a different thread. But if you've got a loop within one thread, making multiple requests, you could easily add it in to the loop to restrict your request rate.
The Sleep
method is overloaded - one signature takes a TimeSpan
and the other takes a number of milliseconds. Personally I'd generally prefer the first one, as it leaves no room for ambiguity. For example:
Thread.Sleep(TimeSpan.FromSeconds(2));
is obviously asking the thread to sleep for 2 seconds - not 2 minutes, 2 milliseconds etc.
OTHER TIPS
System.Threading.Thread.Sleep(x);
…where x
is the number of milliseconds to sleep the thread.
An alternative is to use a Timer
and do a request each time the Tick
event fires.