Task.Delay accuracy

Learning about the accuracy of Task.Delay with small time frames

Home DailyDrop

Daily Knowledge Drop

Task.Delay relies on the underlying operating system's internal timer, which for most Windows environments, takes about 15ms to resolve. This means that the minimum amount of time that can be accurately used with Task.Delay is approximately 15ms (on Windows)


Sample

System.Diagnostics.StopWatch can be used to benchmark how long a Task.Delay call actually takes:

Stopwatch? watch = Stopwatch.StartNew();

await Task.Delay(100);

watch.Stop(); 

Console.WriteLine($"Actual time delayed: {watch.ElapsedMilliseconds} milliseconds");

Executing the above, the result (which may vary each execution and per machine):

Actual time delayed: 110 milliseconds

Even though the code is specifying a 100ms delay, and actual delay is close to 110ms.

The same inaccurate delay is seen when trying to delay for a small precise time:

Stopwatch? watch = Stopwatch.StartNew();

await Task.Delay(5);

watch.Stop(); 

Console.WriteLine($"Actual time delayed: {watch.ElapsedMilliseconds} milliseconds");

The output:

Actual time delayed: 19 milliseconds

Results may vary, but (in my case) the true delay was never less than 17ms. As mentioned, this is due to the underlying operating system's internal timer.


Notes

If requiring small precise waiting times, Task.Delay is not the way to go. In fact there are no "easy" ways to wait for such small precise times - there are ways to do it (which will not be shown here), but they are involved and are often not very performant when it comes to resource usage.


References

Don’t use Task.Delay for small precise waiting times

Daily Drop 240: 23-01-2023

At the start of 2022 I set myself the goal of learning one new coding related piece of knowledge a day.
It could be anything - some.NET / C# functionality I wasn't aware of, a design practice, a cool new coding technique, or just something I find interesting. It could be something I knew at one point but had forgotten, or something completely new, which I may or may never actually use.

The Daily Drop is a record of these pieces of knowledge - writing about and summarizing them helps re-enforce the information for myself, as well as potentially helps others learn something new as well.
c# .net task delay accuracy