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();
}