【问题标题】:Stopwatch.GetTimeStamp causes stackoverflow error?Stopwatch.GetTimeStamp 导致 stackoverflow 错误?
【发布时间】:2011-02-10 18:58:08
【问题描述】:

如果我是正确的,我应该绝对在使用 Stopwatch.GetTimeStamp 时不会遇到 stackoverflow 错误,尤其是仅在启动我的程序之后。

这是我的代码:

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

由 Stopwatch.GetTimeStamp() 放置的 currentTicks。这段代码在一个称为无限的方法中(我用它来控制 FPS)。有人有什么想法吗?

编辑: 主窗体代码:

    Game game;

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

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

        MainLoop();
    }`

然后,游戏类:

    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;
        }
    }

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

【问题讨论】:

  • 该代码在哪里声明?你能展示更多围绕它的代码吗?另外,currentTickslastTicksinterval 是如何声明的?
  • 无法从您提供的 sn-p 中回答。我唯一可以向您保证的是 GetTimeStamp 绝对不是导致此异常的原因。
  • @Skurmedel - 可能,但异常不太可能 IMO
  • 重现问题的邮政编码。这显然不是。
  • 在结束时放轻松,他至少可以有一些时间来编辑他的答案。

标签: c# stopwatch


【解决方案1】:

您正在递归调用 MainLoop(又名 infinite recursion),这意味着您正在溢出 call stack。 GetTimeStamp 在这里是一个红鲱鱼。

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

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

【讨论】:

  • @BloodyAugust: ...这就是为什么发布所有源代码总是很重要的;-)
【解决方案2】:

我猜发布的代码是一个名为currentTickslastTicks 甚至interval 的属性的getter 的一部分。

所以问题是关于使用正确的 Caps 属性。

【讨论】:

  • 如您所见(现在),事实并非如此。
猜你喜欢
  • 1970-01-01
  • 2019-09-14
  • 2015-09-12
  • 2015-04-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多