1

I've been trying to implement a higher precision timer to my C# Raylib game project for running at fixed intervals regardless of the game's main drawing loop. My current implementation is using System.Timers.Timer, but this is too inaccurate for my use, as it tends to fluctuate a lot:

using System.Diagnostics;
using System.Timers;
namespace Engine
{
    partial class Game
    {
        /*For calculating tick delta*/
        static public double TickDelta;
        static private double SecondTick;
        static private Stopwatch? TickWatch;
        /*For calculating tick delta*/

        private static readonly System.Timers.Timer GameTick = new(40);
        public static void InitTick()
        {

            GameTick.Elapsed += Tick;
            GameTick.Start();
            TickWatch = new Stopwatch();
            TickWatch.Start();
        }
        public static void TerminateTick()
        {
            GameTick.Stop();
        }

        public static void Tick(object? sender, ElapsedEventArgs e)
        {
            TimeSpan ts = TickWatch!.Elapsed;
            double ft = ts.TotalMilliseconds;
            TickDelta = ft - SecondTick;
            SecondTick = ts.TotalMilliseconds;
        }
    }
}

When measuring the time span with System.Diagnostics.Stopwatch, the interval seems to fluctuate +-~15ms. I found this timer library on NuGet, which looked very promising at first, but I don't see any versions of .net that support Linux under the "Frameworks" tab. And sure enough, I get errors for missing winmm.dll on my system when attempting to integrate this library.

Are there any other libraries that are known to work/be supported on Linux .net 8.0? Or are there any other timer implementations with event callbacks that only rely on system libraries?

3
  • This one is a very similar question. The answer is from my high-precision timer implementation, which works on every platform. Here is the most up-to-date version of my HiResTimer class. [NuGet] Commented May 11, 2024 at 14:08
  • @marsze: No, it also has about 15.5ms resolution, at least on Windows. That's the exact reason why I had to implement a high resolution timer. Commented May 11, 2024 at 14:16
  • Little late comment, but I think your approach using the timer for the main loop is worth discussion. What if your main loop refresh takes more than the refresh interval by any reason? It seems to me that a better approach could be doing the main loop refresh and then check (Stopwatch.Elapsed) how much time it took and optionally wait till the end of the interval. Commented Aug 14, 2024 at 9:51

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.