Stopwatch.GetTimeStamp 导致堆栈溢出错误?

Blo*_*ust -1 c# stopwatch

如果我是正确的,我在使用 Stopwatch.GetTimeStamp 时绝对不会出现 stackoverflow 错误,尤其是在启动程序后。

这是我的代码:

if (currentTicks >= lastTicks + interval)
        {
            lastTicks = currentTicks;
            return true;
        }
Run Code Online (Sandbox Code Playgroud)

currentTicks 由 Stopwatch.GetTimeStamp() 放置。这段代码位于一个名为“infinitely”的方法中(我用它来控制 FPS)。有人有什么想法吗?

编辑:主表单代码:

    Game game;

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

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

        MainLoop();
    }`
Run Code Online (Sandbox Code Playgroud)

然后,游戏类:

    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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

它停止在“if (currentTicks >= lastTicks +interval)”处。我可以看到 currentTicks 的值为 30025317628568。其他所有内容都无法评估。

Mar*_*rtW 5

您正在递归地调用 MainLoop (又名无限递归),这意味着您正在溢出调用堆栈。GetTimeStamp 在这里是一个转移注意力的事情。

从内部删除对 MainLoop 的调用,只使用标准 while 循环:

while (game.DrawStuff(Stopwatch.GetTimestamp()))
{
    Invalidate();
}
Run Code Online (Sandbox Code Playgroud)