Reputation: 4142
I was under the impression that Thread.Sleep(x)
is not precise and that all it will do is sleep the thread for at minimum x
ms. See here, here and here.
When sleeping for a very low amount of time, e.g. 1ms
, it is expected that you will find that the thread occasionally sleeps for about 15ms
. This is apparently due to clock interrupt rate which by default is 64
times per second.
I tried this a couple of years ago and indeed, I too experienced the 15ms
resolution. However, I have just tried again and now I am seeing 1ms
to 2ms
resolution with very rarely > 2ms.
What has changed? Has .NET changed (I'm using 4.6
at the moment, don't remember what I used 2 years ago)? Perhaps it is the operating system which has changed? (I used and am still using AWS EC2 Windows Server, but perhaps there has been an update.)
My simple test program:
private static Stopwatch sw =new Stopwatch();
static void Main(string[] args)
{
var timer = new Stopwatch();
var results = new List<long>();
for (int i = 0; i < 100000; i++)
{
timer.Restart();
Thread.Sleep(1);
results.Add(timer.ElapsedMilliseconds);
}
foreach (var item in results.Where(x => x > 1).ToList())
{
Console.WriteLine(item );
}
Console.ReadLine();
}
Upvotes: 4
Views: 696
Reputation: 13983
The precision of Thread.Sleep
(and the underlying Windows API Sleep
function in kernel32) is dependent on the resolution of the system clock, which has a default tick rate of roughly 15 ms. Applications can request a higher resolution, in which case the highest requested resolution is used globally.
In this case case, you're likely seeing sub-15 ms resolution because something running on your system has requested a higher resolution.
If your application actually needs sub-15 ms sleeps, it can request a higher resolution via the native timeBeginPeriod function.
However, note that it is possible that the underlying timer device won't support your requested resolution, so it's not good practice to write code that relies on this behavior unless you're absolutely sure of the hardware your code will be running on.
Upvotes: 5