Understanding Thread.Sleep Precision Limitations
The default precision of Thread.Sleep in .NET applications is approximately 15 milliseconds, wich can be insufficient for time-sansitive operations. When calling Thread.Sleep(1), the actual delay often measures around 15.6ms due to system timer resolution constraints.
Using Windows Multimedia Library for Enhanced Precision
The Windows Multimedia Library (winmm.dll) provides functions to adjust system timer resolution. By calling timeBeginPeriod and timeEndPeriod, developers can achieve sleep intervals closer to the intended duration, reducing the actual delay to approximately 0.8ms for a 1ms sleep request.
C# Implementation
using System;
using System.Runtime.InteropServices;
using System.Threading;
public class HighPrecisionTimer
{
[DllImport("winmm.dll", EntryPoint = "timeBeginPeriod")]
public static extern uint SetTimerResolution(uint milliseconds);
[DllImport("winmm.dll", EntryPoint = "timeEndPeriod")]
public static extern uint ResetTimerResolution(uint milliseconds);
public static void TestPreciseSleep()
{
SetTimerResolution(1);
DateTime beginTime = DateTime.Now;
Thread.Sleep(10);
DateTime endTime = DateTime.Now;
TimeSpan elapsed = endTime - beginTime;
Console.WriteLine($"Actual sleep duration: {elapsed.TotalMilliseconds}ms");
ResetTimerResolution(1);
}
}
VB.NET Implementation
Imports System.Runtime.InteropServices
Imports System.Threading
Public Module PrecisionTimer
<DllImport("winmm.dll", EntryPoint:="timeBeginPeriod")>
Public Function BeginPeriod(ByVal period As UInteger) As UInteger
End Function
<DllImport("winmm.dll", EntryPoint:="timeEndPeriod")>
Public Function EndPeriod(ByVal period As UInteger) As UInteger
End Function
Public Sub MeasureSleepAccuracy()
BeginPeriod(1)
Dim startTimestamp As DateTime = DateTime.Now
Thread.Sleep(10)
Dim endTimestamp As DateTime = DateTime.Now
Dim duration As TimeSpan = endTimestamp - startTimestamp
Console.WriteLine($"Measured interval: {duration.TotalMilliseconds}ms")
EndPeriod(1)
End Sub
End Module
This approach modifies the system-wide timer resolution, affecting all processes. Applications should restore the default resolution immediately after completing time-sensitive operations to minimize system impact.