Search code examples
c#.net-4.0polling

Where can I find a good C# console app that demonstrates polling?


I'm looking for a good example of polling in C#.

Basically, every X seconds an instrument is read and the values logged to a text file. I was looking for a sample that makes use of .NET 4's parallel library. Or, maybe I'm overthinking this solution by looking at TPL...

ps- this question is unrelated to my previous question about database polling.


Solution

  • I'm not sure I'd particularly bother with TPL here. Just use System.Threading.Timer or System.Timers.Timer to perform an action periodically. Those will both use the thread pool - what are you planning on doing in the main console thread during this time?

    Of course, another extremely simple option would be to just make the main thread sleep between poll occurrences. It's crude, but if that's all your app needs to do, it may well be good enough for you. I'm not sure how it behaves if the system clock is changed, mind you... is this for a very long-running task for production usage, or just a quick tool? (If it's a long-running app, you might want to consider using a Windows Service instead.)