How to introduce a delay between webrequests to a site in C#? - 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?

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.

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.

Related

dispatcherTimer doesn't work accurately

I need to capture 10 frames per second of a live camera for 15 min. I used dispatcherTimer class but seems it doesn't work accurately. How to make it accurate? I even don't save the image because it is time consuming and i just keep it in the memory but still it doesn't work correctly.
should I use another library?
counter01 = new DispatcherTimer();
counter01.Tick += new EventHandler(counter01_Tick);
counter01.Interval = new TimeSpan(0, 0, 0,100); // every 100 milliseconds == 10 frames per seconds
MSDN states that:
Timers are not guaranteed to execute exactly when the time interval occurs,
but they are guaranteed to not execute before the time interval occurs.
You can check StopWatch, it might help you.
It is as accurate as it can be. Which requires your UI thread to be responsive, quickly dispatching any messages it gets. Including the "time is up" notifications that DispatcherTimer generates, the ones that generate the Tick event.
The usual hangup with seeing DispatcherTimer triggering the Tick event handler late is that you have a firehose problem. In other words, the amount of time required by the event handler is longer than the timer's Interval property value. This takes care of itself in the manner you expect, whenever you try to do more than the machine can handle then whatever you are trying to do just runs later.
No lack of firehose problems with video, one frame can contain a lot of data. A typical hidef video stream runs at 25 frames per second with each frame containing 1920x1080 pixels. That's 25 x 1920 x 1080 x 3 = 148 megabytes/second. Short from decompressing overhead, you can't even write the data to a disk at that rate. Most consumer-level disk drives top out at 30 megabytes/second, give or take a factor of 2. Lowering the frame rate to 10/sec is not enough to solve it, that's still 60 MB/sec, you have to take more drastic measures like reducing the frame size. Or use a good video encoder that can compress video real-time.
This is a systemic problem, not a DispatcherTimer problem. Use a profiler to get more insight, it helps you identify the true bottle-neck.
You actually can get the DispatcherTimer to execute the DispatcherTimer.Tick event every 100 milliseconds on a good PC, but you have to address 2 problems first (see below). However, as others wrote here correctly, the processing of a frame will take some time too and the fastest reliable tick frequency might only be 5 ticks per second, if the frame processing itself takes about 100 milliseconds.
1) Choose higher DispatcherTimer.Priority
The DispatcherTimer runs on the WPF GUI thread. The advantage of this is that the code of DispatcherTimer.Tick can access any WPF control. The WPF GUI thread is controlled by a Dispatcher, which has a priority queue for activities the WPF GUI thread wants to execute. Rendering related activities have a higher priority than the DispatcherTimer has per default. The default priority of the DispatcherTimer is DispatcherPriority.Background. With this priority, the Tick can execute on my PC not faster than every 100..300 milliseconds. However, create the timer like this: new DispatcherTimer (DispatcherPriority.Input) and it will fire about 100..200 milliseconds. Rendering will still have a higher priority, so the user does not get a frozen GUI.
2) Improve Tick regularity
One problem with the DispatcherTimer is that if the Tick event gets delayed by x milliseconds because the WPF GUI thread is busy with other activities, the next Tick will still wait for 100+ milliseconds. However, if you shorten DispatcherTimer.Interval by x milliseconds, you will get a more regular firing of the tick event.
For more details see my article on CodeProject: Improving the WPF DispatcherTimer Precision
Final Consideration
Why do you want to process the frames on the WPF GUI thread ? Use a DispatcherTimer only if the Tick event has little to do and needs access to the WPF controls. However, if you need to execute quite some code every 100 milliseconds, better use an additional thread. Your CPU has different cores and it is a good idea to distribute the workload over 2 cores.

Ten times Thread.Sleep(100) or a single Thread.Sleep(1000)?

Is there a difference (from performance perspective) between:
Thread.Sleep(10000);
and
for(int i=0; i<100; i++)
{
Thread.Sleep(100);
}
Does the single call to Thread.Sleep(10000) also results in context switches within this 10 seconds (so the OS can see if it's done sleeping), or is this thread really not served for 10 seconds?
The second code (for loop) requires more process swaps and should be little slower than Thread.Sleep(10000);
Anyway you can use System.Diagnostics.Stopwatch class to determine the exact time for these two approaches. I believe the difference will be very very small.
in any case second loop will take time because of following overheads
Memory utilization for 10 different thread objects
10 different callbacks will be initiated once you call thread.sleep
Overhead cost for running loop
if we want to run the code on single thread so why do we want a loop if we don't have any break point even.

Which way is better, and how to pass parameters to windows.forms.timer

What I want to accomplish it the following thing:
I have a lot of "checks(if/else if etc)" inside a timer, that his interval is 1000 ms,
there is a text file that getting updated and the timer read it every 1000 ms and check for some specific changes,
under 1 of those conditions if it is true the timer, i need to wait 10 sec and then read another text file and then continue with the rest of the timer code.
but in the mean time the timer keep running under those 10 sec and preform the checks every 1sec for all the other conditions and this 1 also.
what i thought to do it
if the conditions i wanted it true i will start a new timer with 10sec interval and it will continue with the code of that specific part.
but what i have hard time to accomplish is how to pass parameters into that timer
such as
newTimer.Start(int "parameter", string "parameter b", list<string> parameters c")
etc etc
or if you got any other idea i will be glad to hear.
To pass parameters, you can always use Tuple.
newTimer.Start(Tuple.Create(param1, param2, param3));
You might not need to have two timer if you do the logic correctly.
Timer *run every second*
Check file
If file has flag Then save in variable the current date + 10 seconds
If current date > saved date Then Check the other file
You need to consider that a System.Windows.Forms.Timer will run on the GUI thread (the thread that run the containing form's message loop / pump), as it uses window messages (WM_TIMER) that are processed by the GUI thread. Because of that, any code that runs under any System.Windows.Forms.Timer in your form will execute synchronously. So, if your start a new System.Windows.Forms.Timer which blocks for 10 seconds, all your other timers will be blocked as well (since the message loop is blocked).
Consider using a System.Threading.Timer or System.Timers.Timer, as they run the timer callback on a different thread. This way, your code will run pretty much as you'd want - every one second the method will be running, regardless of weather the previous call completed or is still blocking (waiting 10 seconds).

Acceptable use of Thread.Sleep()

I'm working on a console application which will be scheduled and run at set intervals, say every 30 minutes. Its only purpose is to query a Web Service to update a batch of database rows.
The Web Service API reccommends calling once every 30 seconds, and timeout after a set interval. The following pseudocode is given as an example:
listId := updateList(<list of terms>)
LOOP
WHILE NOT isUpdatingComplete(listId)
END LOOP
statuses := getStatuses(“LIST_ID = {listId}”)
I have coded this roughly in C# as:
int callCount = 0;
while( callCount < 5 && !client.isUpdateComplete(listId, out messages) )
{
listId = client.updateList(options, terms, out messages);
callCount++;
Thread.Sleep(30000);
}
// Get resulting status...
Is it OK in this situation to use Thread.Sleep()? I'm aware it is not generally good practice but from reading reasons not to use it this seems like acceptable usage.
Thanks.
Thread.Sleep ensures the current thread doesn't return until at least the specified milliseconds have passed. There are plenty of places it's appropriate to do that, and your example seems fine, assuming it's running on a background thread.
Some example places you don't want to use it - on the UI thread or where you need to do exact timing.
Generally speaking, Thread.Sleep is like any other tool: perfectly OK to use, except when it's terribly misused. I disagree with the "not generally good practice" part, which is the result of people abusing Thread.Sleep when they should be doing something else (i.e. blocking on a synchronization object).
In your case the program is single-threaded, it has no UI (i.e. the thread has no message loop) and you do not want to synchronize with external events. Therefore Thread.Sleep is just fine.
The general objection against Sleep() is that it wastes a Thread.
In your case there is only 1 Thread (maybe 2) so that is not really a problem.
So I think it looks fine (but I would sleep 29 seconds to cut some slack).
It's fine, except that you cannot interrupt it once it goes into sleep, without aborting the thread (which is not recommended).
That's why a ManualResetEvent might be a better idea, since it can be signalled ("awaken") from a different thread.
you could stick with the Thread.Sleep method. But it would be more elegant to schedule it to run every 30 minutes - so you don't have to take care of the waiting inside your application.
Thread.Sleep isn't the best for executing periodic logic. Thread.Sleep(n) means your thread will relinquish control for n milliseconds. There is no guarantee that it will regain control after n milliseconds, it depends on the CPU load.
If you are locking the thread for 30 mins case you should schedule a windows task every 30 mins, so the program executes and then ends. That way you are not locking a thread for so long.
For shorter times, like 30 secs / 1 min, System.Thread.Sleep() is perfectly fine. For more than 5 mins i would use a windows task. (Im spanish i think on the english version are called like that, im talking about the tasks you schedule from the control panel ;-) )

Timer is starting late, hence shows the time which is a second late then actual time

I have a timer. But it starts a second late.I mean, i am clocking a time according to the timer. But the time in the clock, which updates through timer, is one second less then the actual time elapsed. The timer starts off a second late. How to set my timer to start at right time to show actual time? this is the code inside tick event:
if (currentState == play)
{
m_StatusLabel.Text = String.Format("Playing {0} ", format(timeCounter));
timeCounter++;
}
Here timeCounter is updating with each second.
Standard System.Windows.Forms timers give no guarantees about 'metronome quality'. For that, you would need either a Systems.Threading.Timer or a System.Timer.
Ref: Comparing the Timer Classes in the .NET Framework Class Library
There are no timers available that will gaurantee true-time accuracy, not even System.Threading.Timer can do that. For example, when you ask Threading.Timer to fire in 30ms, it might actually take 40ms or 200ms. Or if you ask for 1 second, it might fire in 1.01 seconds. In won't take long before your time is inaccurate.
The reason for this is that the timer makes the callback thread schedulable, but it still takes time for the thread scheduler to actually call the thread. Various operations the system is performing can delay that callback.
A Windows timer makes only one guarantee: it won't fire before the timeout interval elapses. Specifically, a thread will never receive a timer event while there are messages in its message queue.
Consequently you can't use timers to implement a clock. If you want to update a status message to show how long something has been playing, then you could try this: record the start time, and when your timer ticks get the current time, subtract the start time, and dislay the difference. Your status message won't be updated exactly every second, but when it is updated it will be correct.
Show a number 1 greater:
if (currentState == play)
m_StatusLabel.Text = String.Format("Playing {0} ",
format(++timeCounter) );
NOTE
Please consider the reason of those who suggested displaying the elapsed time as current time - start time. That is the way this is usually done. It is more accurate; a timer can be irregular on a busy system. It is still possible to update the displayed value every second. Pseudo code here for now(). This requires acquiring current time and performing a time difference.
if (currentState == play)
m_StatusLabel.Text = String.Format("Playing {0} ",
format( (now() - start)/1000 );
See Also:
1. DateTime.Subtraction
2. DateTime.Now

Categories