I'm trying to update the UI periodically, System.Windows.Forms.Timer
seems to be the obvious choice since it runs on the UI thread, however there's a note on MSDN page Timer Class says:
The Windows Forms Timer component is single-threaded, and is limited to an accuracy of 55 milliseconds. If you require a multithreaded timer with greater accuracy, use the Timer class in the System.Timers namespace.
This makes me think the possible interval values would be the multiples of 55, but it's not:
private Stopwatch _systemTimersTimerStopwatch = Stopwatch.StartNew();
private Stopwatch _windowsFormsTimerStopwatch = Stopwatch.StartNew();
private long _systemTimersTimerLastElapsed;
private long _windowsFormsTimerLastElapsed;
private void SystemTimersTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
//if (InvokeRequired) {
BeginInvoke(new MethodInvoker(delegate {
long elapsed = _systemTimersTimerStopwatch.ElapsedMilliseconds;
if (_systemTimersTimerLastElapsed != 0) {
Console.WriteLine($"+ System.Timers.Timer: {elapsed - _systemTimersTimerLastElapsed,2} ms");
}
_systemTimersTimerLastElapsed = _systemTimersTimerStopwatch.ElapsedMilliseconds;
}));
//}
}
private void WindowsFormsTimer_Tick(object sender, EventArgs e)
{
long elapsed = _windowsFormsTimerStopwatch.ElapsedMilliseconds;
if (_windowsFormsTimerLastElapsed != 0) {
Console.WriteLine($"- Windows.Forms.Timer: {elapsed - _windowsFormsTimerLastElapsed,2} ms");
}
_windowsFormsTimerLastElapsed = _windowsFormsTimerStopwatch.ElapsedMilliseconds;
}
Interval
properties of both are set to 1, outputs:
+ System.Timers.Timer: 15 ms
- Windows.Forms.Timer: 15 ms
+ System.Timers.Timer: 16 ms
- Windows.Forms.Timer: 20 ms
+ System.Timers.Timer: 15 ms
- Windows.Forms.Timer: 10 ms
+ System.Timers.Timer: 16 ms
- Windows.Forms.Timer: 18 ms
+ System.Timers.Timer: 16 ms
- Windows.Forms.Timer: 14 ms
Clearly System.Windows.Forms.timer
is capable of accuracy lower than the "55 milliseconds" mentioned on MSDN page, where was this number even came from? There's another MSDN page titled Limitations of the Windows Forms Timer Component's Interval Property doesn't mention this "55 milliseconds" limit.
Also, is there any advantage of using a System.Timers.Timer
over System.Windows.Forms.Timer
for my use case? My guess is no since I'd need to use BeginInvoke
anyway.