title: Why are .NET timers limited to 15 ms resolution?
body: <p>Note that I'm asking about something that will call a callback function more often than once every 15 ms using something like <code>System.Threading.Timer</code>.  I'm not asking about how to accurately time a piece of code using something like <code>System.Diagnostics.Stopwatch</code> or even <code>QueryPerformanceCounter</code>.</p>
  
  <p>Also, I've read the related questions:</p>
  
  <p><a href="https://stackoverflow.com/questions/448761/accurate-windows-timer-system-timers-timer-is-limited-to-15-msec">Accurate Windows timer? System.Timers.Timer() is limited to 15 msec</a></p>
  
  <p><a href="https://stackoverflow.com/questions/163022/high-resolution-timer-in-net">High resolution timer in .NET</a></p>
  
  <p>Neither of which supplies a useful answer to my question.</p>
  
  <p>In addition, the recommended MSDN article, <a href="http://msdn.microsoft.com/en-us/magazine/cc163996.aspx" rel="noreferrer">Implement a Continuously Updating, High-Resolution Time Provider for Windows</a>, is about timing things rather than providing a continuous stream of ticks.</p>
  
  <p>With that said. . .</p>
  
  <p>There's a whole lot of bad information out there about the .NET timer objects.  For example, <code>System.Timers.Timer</code> is billed as "a high performance timer optimized for server applications."  And <code>System.Threading.Timer</code> is somehow considered a second class citizen.  The conventional wisdom is that <code>System.Threading.Timer</code> is a wrapper around Windows <a href="http://msdn.microsoft.com/en-us/library/ms686796(v=VS.85).aspx" rel="noreferrer">Timer Queue Timers</a> and that <code>System.Timers.Timer</code> is something else entirely.</p>
  
  <p>The reality is much different.  <code>System.Timers.Timer</code> is just a thin component wrapper around <code>System.Threading.Timer</code> (just use Reflector or ILDASM to peek inside <code>System.Timers.Timer</code> and you'll see the reference to <code>System.Threading.Timer</code>), and has some code that will provide automatic thread synchronization so you don't have to do it.  </p>
  
  <p><code>System.Threading.Timer</code>, as it turns out <em>is not</em> a wrapper for the Timer Queue Timers.  At least not in the 2.0 runtime, which was used from .NET 2.0 through .NET 3.5.  A few minutes with the Shared Source CLI shows that the runtime implements its own timer queue that is similar to the Timer Queue Timers, but never actually calls the Win32 functions.</p>
  
  <p>It appears that the .NET 4.0 runtime also implements its own timer queue.  My test program (see below) provides similar results under .NET 4.0 as it does under .NET 3.5.  I've created my own managed wrapper for the Timer Queue Timers and proved that I can get 1 ms resolution (with quite good accuracy), so I consider it unlikely that I'm reading the CLI source wrong.</p>
  
  <p>I have two questions:</p>
  
  <p>First, what causes the runtime's implementation of the timer queue to be so slow?  I can't get better than 15 ms resolution, and accuracy seems to be in the range of -1 to +30 ms.  That is, if I ask for 24 ms, I'll get ticks anywhere from 23 to 54 ms apart.  I suppose I could spend some more time with the CLI source to track down the answer, but thought somebody here might know.</p>
  
  <p>Second, and I realize that this is harder to answer, why not use the Timer Queue Timers?  I realize that .NET 1.x had to run on Win9x, which didn't have those APIs, but they've existed since Windows 2000, which if I remember correctly was the minimum requirement for .NET 2.0.  Is it because the CLI had to run on non-Windows boxes?</p>
  
  <p>My timers test program:</p>
  
  <pre><code>using System;
  using System.Collections.Generic;
  using System.Diagnostics;
  using System.Threading;
  
  namespace TimerTest
  {
      class Program
      {
          const int TickFrequency = 5;
          const int TestDuration = 15000;   // 15 seconds
  
          static void Main(string[] args)
          {
              // Create a list to hold the tick times
              // The list is pre-allocated to prevent list resizing
              // from slowing down the test.
              List&lt;double&gt; tickTimes = new List&lt;double&gt;(2 * TestDuration / TickFrequency);
  
              // Start a stopwatch so we can keep track of how long this takes.
              Stopwatch Elapsed = Stopwatch.StartNew();
  
              // Create a timer that saves the elapsed time at each tick
              Timer ticker = new Timer((s) =&gt;
                  {
                      tickTimes.Add(Elapsed.ElapsedMilliseconds);
                  }, null, 0, TickFrequency);
  
              // Wait for the test to complete
              Thread.Sleep(TestDuration);
  
              // Destroy the timer and stop the stopwatch
              ticker.Dispose();
              Elapsed.Stop();
  
              // Now let's analyze the results
              Console.WriteLine("{0:N0} ticks in {1:N0} milliseconds", tickTimes.Count, Elapsed.ElapsedMilliseconds);
              Console.WriteLine("Average tick frequency = {0:N2} ms", (double)Elapsed.ElapsedMilliseconds / tickTimes.Count);
  
              // Compute min and max deviation from requested frequency
              double minDiff = double.MaxValue;
              double maxDiff = double.MinValue;
              for (int i = 1; i &lt; tickTimes.Count; ++i)
              {
                  double diff = (tickTimes[i] - tickTimes[i - 1]) - TickFrequency;
                  minDiff = Math.Min(diff, minDiff);
                  maxDiff = Math.Max(diff, maxDiff);
              }
  
              Console.WriteLine("min diff = {0:N4} ms", minDiff);
              Console.WriteLine("max diff = {0:N4} ms", maxDiff);
  
              Console.WriteLine("Test complete.  Press Enter.");
              Console.ReadLine();
          }
      }
  }
  </code></pre>