I am looking for any timer's design, which can schedule tasks with the period less than 1 millisecond. The most optimal scenario: load 25% of 1 core, when 1 separate thread is used for running this pattern.
1 millisecond is the limit for all the timers, which I know:
- System.Windows.Forms.Timer
- System.Timers.Timer
- System.Threading.Timer
I have already implemented timer, which runs task every X microseconds. But it is still loading almost one core, when 1 separate thread is used for running this pattern.
The code:
private readonly TimeSpan _period;
private readonly Stopwatch _stopwatch;
private TimeSpan _lastElapsedTime;
private Double _iterationsPerPeriod;
void Run()
{
TimeSpan elapsed = _stopwatch.Elapsed;
TimeSpan interval = elapsed - _lastElapsedTime;
if (interval < _period)
{
Int32 iterationsToWait = (Int32) (_iterationsPerPeriod * (interval.TotalMilliseconds / _period.TotalMilliseconds));
Thread.SpinWait(iterationsToWait);
}
_lastElapsedTime = _stopwatch.Elapsed;
// RunTask();
}
void RunTimer()
{
while(true)
{
Run();
}
}
How can I run a method every X microseconds without CPU loading?