private void Run(object state)
{
long lastMs = 0;
var sw = Stopwatch.StartNew();
long lastFpsCheck = 0;
var actualFps = 0;
// Move to running state
Interlocked.Exchange(ref _state, 2);
_started();
while (Interlocked.Read(ref _state) == 2)
{
var frameMs = (int)Math.Round(1000.0 / FPS);
long delta = (lastMs + frameMs) - sw.ElapsedMilliseconds;
// Actual FPS check, update every second
if ((lastFpsCheck + 1000 - sw.ElapsedMilliseconds) <= 0)
{
_actualFpsUpdate(actualFps);
lastFpsCheck = sw.ElapsedMilliseconds;
actualFps = 0;
}
if (delta <= 0)
{
// Time to call the callback!
actualFps++;
_callback(Interlocked.Increment(ref _frameId));
lastMs = sw.ElapsedMilliseconds;
}
else
{
Thread.Yield();
}
}
// Move to stopped state
Interlocked.Exchange(ref _state, 0);
Interlocked.Exchange(ref _frameId, 0);
sw.Stop();
_stopped();
}
}