Stopwatch.GetTimeStamp causes stackoverflow error?

472 Views Asked by At

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.

2

There are 2 best solutions below

1
On BEST ANSWER

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();
}
1
On

I'm guessing the posted code is part of the getter of a property callled currentTicks, lastTicks or even interval.

And so the question turns out to be about using proper Caps for properties.