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 a开发者_如何学Ct TPL...
ps- this question is unrelated to my previous question about database polling.
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.)
It's real easy to create a timer:
static void Main(string[] args)
{
// Create a timer that polls once every 5 seconds
var timer = new System.Threading.Timer(TimerProc, null, 5000, 5000);
Console.WriteLine("Polling every 5 seconds.");
Console.WriteLine("Press Enter when done:");
Console.ReadLine();
timer.Dispose();
}
static int TickCount = 0;
static void TimerProc(object state)
{
++TickCount;
Console.WriteLine("tick {0}", TickCount);
}
Note that the TimerProc
is called on a separate thread. Your main program can do other things, and this will continue to poll every five seconds until you kill (or modify) the timer.
I prefer System.Threading.Timer
over System.Timers.Timer
because the latter swallows exceptions. If there is a bug in your elapsed event handler that throws an exception, you'll never know about it because the System.Timers.Timer
event handler will suppress the exception. For that reason, I strongly suggest that you not use it. Use System.Threading.Timer
instead.
Using the PL doesn't sound correct to me for this task. I recommend checking out System.Timer with which you can specify a recurring interval at which the Elapsed event is raised in your application allowing you to handle the event to perform regular processing.
精彩评论