I have an application that needs to check a website feed every second.
Sometimes the request to the server is longer than a second. In this case, the application needs to wait until the first request completes, then start a new request immediately. How could I implement this?
Also, the request should not freeze the GUI.
I would use a simple variation of the producer-consumer pattern. You’d have two theads, a producer and a consumer, that share an integer variable. The producer would have a
System.Threading.Timerthat fired every second, at which time it wouldInterlocked.Incrementthe variable and call the consumer. The consumer logic repeatedly checks the feed andInterlocked.Decrementthe counter, while the counter is greater than zero. The consumer logic would be protected by aMonitor.TryEnterwhich would handle re-entrancy. Here’s sample code.Usage:
A good resource on .NET Threading (besides the MSDN Library stuff) is Jon Skeet’s documentation, which includes this example of producer-consumer under “More
Monitormethods”.By the way, a true producer-consumer pattern revolves around a collection of work data, with one or more threads producing work by adding data to that collection, while one or more other threads consumer work by removing data from that collection. In our variation above, the “work data” is merely a count of the number of times we need to immediately check the feed.
(Another way to do it, instead of having the timer callback call Consume, is for the timer callback to lock and pulse a
Monitorthat Consume waits on. In that case, Consume has an infinite loop, likewhile(true), which you kick off one time in its own thread. Therefore there is no need to support re-entrancy with the call toMonitor.TryEnter.)