In my previous question how to suspend a thread for 1 ms? it was answered that to introduce delay of 1 ms I should use Timer.
I need to “do work” then wait 2 ms in average (1-5 ms is ok, it’s ok to have rarely extreme delays up to several hundreads ms), then do work again. It’s important not to try to start new iteration when previous iteration still not finished, so I don’t need to do something every 1-5 ms, I need 1-5 ms delay between iterations.
I’ve tried to do that using System.Timers.Timer but it doesn’t work:
using System;
using System.Diagnostics;
using System.Threading;
using System.Timers;
using Timer = System.Timers.Timer;
namespace TestTimer
{
class Program
{
static Timer refresh_timer;
private static int called;
private const int ITERATIONS = 100;
private static Stopwatch sw;
static void Main(string[] args)
{
refresh_timer = new Timer(1);
refresh_timer.AutoReset = false;
refresh_timer.Elapsed += OnRefreshTimedEvent;
sw = Stopwatch.StartNew();
refresh_timer.Start();
Thread.Sleep(10000);
}
static void OnRefreshTimedEvent(object source, ElapsedEventArgs args)
{
DoGateIteration();
}
private static void DoGateIteration()
{
//try
//{
// work here
called++;
//}
//finally
//{
if (called == ITERATIONS)
{
Console.WriteLine("Average iterations per second: " + ITERATIONS * 1000 / sw.ElapsedMilliseconds);
Console.WriteLine("Average iterations milliseconds: " + sw.ElapsedMilliseconds / ITERATIONS);
}
refresh_timer.Start();
//}
}
}
}
It reports:
Average iterations per second: 64
Average iterations milliseconds: 15
So it seems System.Timers.Timer is not as precise as I need.
Probably I should try System.Threading.Timer, but this timer doesn’t have AutoReset property that I need.
What would you suggest?
For such a short delay of only 1 or 2 milliseconds, it’s probably best just to busy-wait:
Output: