I am 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 wait for X seconds before proceeding?
Asked
Active
Viewed 2,593 times
2 Answers
6
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.

Jon Skeet
- 1,421,763
- 867
- 9,128
- 9,194
-
+1 For mentioning feeding `Sleep` a `TimeSpan`. That's a good idea that I'd never really thought about. – Brian Jan 03 '11 at 14:16
-
Thread.Sleep may not work because "If there are no other threads of equal priority that are ready to run, execution of the current thread is not suspended." - msdn doc – an phu Feb 04 '22 at 09:17
-
1@anphu: That's in the context of "If the value of the millisecondsTimeout argument is zero, the thread relinquishes the remainder of its time slice to any thread of equal priority that is ready to run." If you call `Thread.Sleep` with an actual positive (and non-negligible) amount of time to sleep, it *doesn't* just ignore it. – Jon Skeet Feb 04 '22 at 09:28
1
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.

Jay
- 56,361
- 10
- 99
- 123