gpt4 book ai didi

.net - Windows 窗体计时器错误或使用不当?

转载 作者:可可西里 更新时间:2023-11-01 10:10:11 24 4
gpt4 key购买 nike

在使用 Windows 窗体编写小型 OpenGL 应用程序时,我发现了一些我认为非常靠不住的性能分析器。

我正在使用 System::Windows::Forms::Timer检测鼠标空闲和其他一些用户输入的组合。滴答功能很有用,但有时我想“重置”计时器。你不能直接这样做,但你可以通过这样做得到正确的效果:

this->someTimer->Stop();
this->someTimer->Start();

定时器间隔为50ms。有时我这里的“重置”代码每 30 毫秒运行一次。令我惊讶的是,这是一件非常费力的事情——我的程序执行的 30% 通常在这两行中!这不是经常调用这两条线的情况。在某些人为设计的情况下,此代码的调用频率与例如 OpenGLSwapBuffers() 一样,但仅此而已。我将其解释为这两条线的成本大约是我整个渲染循环的一半!

目前我正在使用一种变通方法,但计时器方法更优雅一些。我很好奇——为什么这两条线的计算成本如此之高?我错过了什么?有没有更好的方法来重置计时器?

最佳答案

调用 Start() 和 Stop() 设置一个内部“启用”标志,每次设置(在 Start 的情况下)或取消设置(在 Stop 的情况下)时执行以下工作:

public virtual void set_Enabled(bool value)
{
lock (this.syncObj)
{
if (this.enabled != value)
{
this.enabled = value;
if (!base.DesignMode)
{
if (value)
{
if (this.timerWindow == null)
{
this.timerWindow = new TimerNativeWindow(this);
}
this.timerRoot = GCHandle.Alloc(this);
this.timerWindow.StartTimer(this.interval);
}
else
{
if (this.timerWindow != null)
{
this.timerWindow.StopTimer();
}
if (this.timerRoot.IsAllocated)
{
this.timerRoot.Free();
}
}
}
}
}
}

如您所见,其中涉及处理分配和管理等工作,而不仅仅是设置内部标志。这可能是您遇到的问题的代价。

作为您问题的可能解决方案,我想提请您注意以下事实:.NET Framework 中存在三种计时器实现:

  • System.Timers.Timer
  • System.Threading.Timer
  • System.Windows.Forms.Timer

System.Timers.Timer 和 System.Threading.Timer 实现是计时器功能的轻量级实现,您应该调查其中一个更轻量级的实现是否性能更高并且仍能满足您项目的要求。有关实现之间的功能差异,请参阅 this blog post from Mark Michaelis .

关于.net - Windows 窗体计时器错误或使用不当?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1665232/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com