Is .NET Timer more reliable than VB6 Timer
In the good old days of VB6 you could not rely on the timer control to fire at exactly the specified interval. If your program was doing some intense processing the Timer_Tick event i开发者_JAVA百科s pushed onto the stack and only when it gets to the instruction is it processed, which may be some seconds(?) later.
So my question is - has the .NET timer control been improved such that this can be relied upon to fire at exactly the time interval specified? I guess the above still applies doesn't it? But is it any better than the VB6 version?
Are there any alternatives to using the timer control that ensure that an event fires after a specified interval?
System.Windows.Forms.Timer
runs on the UI thread and relies on a message pump; it works essentially in the same way as a VB6 timer.
But .NET has other timers - System.Threading.Timer
, System.Timers.Timer
that use worker threads in a multi-threaded environment.
Which is "better" depends on your requirement - using a multithreaded timer may fire more nearly at the requested interval, but this comes at the cost of the added complexity inherent in using threading.
The problem with Timers is that it's OS dependent in a sense. The timer work has to be scheduled by the OS and if there's another high priority process using up a lot of the processing power then it might decide to schedule your code to run at a later time giving more time for another more important line of work to progress.
For the most part newer timers are probably more reliable but they are only as reliable as the subsystem is. I'm not sure if windows implements hardware timers (which are more reliable) or if the .NET VB uses it if it does but from what I've worked with in the past it seems to be hit or miss. Most of the time it's almost dead on within a very small margin and other times I've seen it get delayed by up to a second under certain conditions.
My advice is don't use sleeps and use Timers instead and you shouldn't have very many problems.
P.S: It is relatively difficult for it to happen at EXACT time intervals, there will usually be a couple of milliseconds difference so you shouldn't rely on very very exact Timer granularity.
精彩评论