User Tools

Site Tools

blog:2023-04-13_c_about_.net_timer_component



2023-04-13 C#: About .NET Timer Component

More Detail

  • Windows 7 introduced timer coalescing, which allows scheduled timers to specify a tolerable delay for timer expiration. For example, a scheduled timer that has a period of 200 ms may specify a tolerance of 20 ms.

Recommendations for Application Developers

  • The document also memo recommand thre software should specify a minimum tolerable delay of 32 ms, which corresponds to the duration of two default system clock intervals of 15.6 ms each. If possible, a larger tolerable delay, such as 50 ms, is preferred. Also, the tolerable delay can often scale up with the period of the timer. For example, a 500ms timer might use a 50-ms tolerable delay, whereas a 10-second timer could use a 1second tolerable delay.
  • The key consideration when developers migrate periodic activity to use software timers that can be coalesced is that the period between successive timer expirations is not guaranteed. The duration of time between any two timer expirations is within the range of the period of the timer, plus or minus the tolerable delay.

The minimum interval of the timer component

  • Refer this article.
  • In C#, the minimum interval of the timer (Timer) is 15 milliseconds. This is because the time precision of the Windows operating system is 15 milliseconds, so when the Interval property of the timer is set to less than 15 milliseconds, the timer will be automatically set to 15 milliseconds.
  • This article also show how to implement smaller time intervals in C# by using High Resolution Timer. A high-precision timer is a timer that can provide time precision at the microsecond level, and it can be implemented through Windows API functions.
  • Here is the demo code form the article.
    using System.Runtime.InteropServices;
    public class HighResolutionTimer
    {
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceCounter(out long lpPerformanceCount);
    
        [DllImport("Kernel32.dll")]
        private static extern bool QueryPerformanceFrequency(out long lpFrequency);
    
        private long startTime;
        private long stopTime;
        private long frequency;
    
        public HighResolutionTimer()
        {
            QueryPerformanceFrequency(out frequency);
        }
    
        public void Start()
        {
            QueryPerformanceCounter(out startTime);
        }
    
        public void Stop()
        {
            QueryPerformanceCounter(out stopTime);
        }
    
        public double Duration()
        {
            return (double)(stopTime - startTime) / (double)frequency;
        }
    }

References

TAGS

  • 75 person(s) visited this page until now.

Permalink blog/2023-04-13_c_about_.net_timer_component.txt · Last modified: 2023/04/13 13:53 by jethro

oeffentlich