Windows is not an operating system, so timers are not guaranteed to work for sure. Typical system clocks have an accuracy of about 15 ms. However, you can get more accurate events than the standard System.Threading.Timer
. The Windows API has timers designed for multimedia scripts that can fire at more precise intervals. I am updating the code in the GitHub repository that I support, HighPrecisionTimer , which uses this API to enable the MultimediaTimer.Delay
method based on the task:
private static async Task RunEveryMillisecond(CancellationToken token) { Stopwatch s = Stopwatch.StartNew(); TimeSpan prevValue = TimeSpan.Zero; int i = 0; while (true) { Console.WriteLine(s.ElapsedMilliseconds); await MultimediaTimer.Delay(1, token); if (Console.KeyAvailable) { return; } i++; } }
Please note that this works approximately every 1.5 ms on my system, and it can still hit the processor for about 10% at startup, so that it does not neglect to hit system resources. The standard timer method included in the project is a bit more accurate and efficient (less processor costs, ~ 1%) to run methods at the 1 ms level. I assume that the task-based delay method has more distribution and garbage collection costs.
Please note that using this API can have side effects, such as shortening battery life. However, this is useful for test-type scenarios where shorter timings are required.
source share