Search code examples
c#httpwebrequestdelayed-execution

How to introduce a delay between webrequests to a site in C#?


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?


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.