I'm trying to figure out what should be the best method to do the following? I have a console application that works with httpwebrequest. In some part of my app I would like to do this:
agent.GetURL("http://site.com/etc.../");
Wait for 8-16 Seconds<-Should be random
Agent.GetURL("http://site.com/etc.../");
Wait for 4-6 Seconds etc...
request are time sensitive so the computer time should be different from each request I can't just request wait for it done and request again. I have read around about timers, thread.sleep. I afraid I don't have experience with stopping or pausing Don't want to come up with problems in the future. So if you can advice me what best method will be for this kind of code?
And Is it possible the timer/thread.sleep to be inside a function and use it when ever I need?
Thanks!
Edit: This program is invisible so I need a solution with out loading circle mouse :)
Try
Random random = new Random();
int timeDelay = random.Next(8, 16);
Thread.Sleep(timeDelay * 1000); //time in milliseconds
This question provides a method to generate random numbers in a defined range, you can take that as-is and wrap it in another method to pause for a random number of seconds.
Code could look like this:
// Method from the linked answer, copy-pasted here for completeness
// added the relevant fields because the original code is an override
public Int32 GetNewRandomNumber(Int32 minValue, Int32 maxValue)
{
RNGCryptoServiceProvider _rng = new RNGCryptoServiceProvider();
byte[] _uInt32Buffer = new byte[4];
if (minValue > maxValue)
throw new ArgumentOutOfRangeException("minValue");
if (minValue == maxValue) return minValue;
Int64 diff = maxValue - minValue;
while (true)
{
_rng.GetBytes(_uint32Buffer);
UInt32 rand = BitConverter.ToUInt32(_uint32Buffer, 0);
Int64 max = (1 + (Int64)UInt32.MaxValue);
Int64 remainder = max % diff;
if (rand < max - remainder)
{
return (Int32)(minValue + (rand % diff));
}
}
}
public void RandomWait(int minWait, int maxWait)
{
// Thread.Sleep() wants a number of milliseconds to wait
// We're going, as an example, to wait between 8 and 16 seconds
System.Threading.Thread.Sleep(GetNewRandomNumber(8, 16) * 1000);
}
Then you just call RandomWait()
when you need it.
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