Search code examples
c#stopwatch

Stopwatch.GetTimeStamp causes stackoverflow error?


If I'm correct, I should definitely not be getting a stackoverflow error while using Stopwatch.GetTimeStamp, especially only directly after starting my program.

Here's my code:

if (currentTicks >= lastTicks + interval)
        {
            lastTicks = currentTicks;
            return true;
        }

currentTicks being placed in by Stopwatch.GetTimeStamp(). This bit of code is in a method called infinitely (I'm using it to control FPS). Anybody have any ideas?

EDIT: Main form code:

    Game game;

    public Form1()
    {
        InitializeComponent();
        game = new Game(Stopwatch.Frequency / 45);
        MainLoop();
    }

    public void MainLoop()
    {
        if (game.DrawStuff(Stopwatch.GetTimestamp()))
        {
            Invalidate();
        }

        MainLoop();
    }`

Then, the Game class:

    public long lastTicks { get; set; }

    public double interval { get; set; }

    public Game(double Interval)
    {
        interval = Interval;
    }

    public bool DrawStuff(long currentTicks)
    {
        if (currentTicks >= lastTicks + interval)
        {
            lastTicks = currentTicks;
            return true;
        }

        else
        {
            return false;
        }
    }

It stops on "if (currentTicks >= lastTicks + interval)". I can see the value of currentTicks is 30025317628568. Everything else cannot be evaluated.


Solution

  • You're calling MainLoop recursively (aka infinite recursion), which means that you're overflowing the call stack. GetTimeStamp is a red herring here.

    Remove the call to MainLoop from within itself and just use a standard while loop :

    while (game.DrawStuff(Stopwatch.GetTimestamp()))
    {
        Invalidate();
    }