【问题标题】:Control.ValueChanged fire with time offsetControl.ValueChanged 触发时间偏移
【发布时间】:2019-01-09 17:10:12
【问题描述】:

我有一些 C# 控件,例如 NumericUpDownTextBox,并希望以几秒的偏移量触发事件。过去,我使用Timer 完成了这种行为。我正在编写的代码使用BackgroundWorker 来完成此操作。在其他一些地方,我发现了正常的线程来构建这种行为。

可能需要偏移量的原因是,例如,在 NumericUpDown 的每次 ValueChange 之后执行的耗时方法。如果用户多次单击向下箭头,则只有最后一次单击才是重要的,因为这是用户最终想要的值。

我过去的处理方式如下

private void numericUpDown1_ValueChanged(object sender, EventArgs e)
{
    /*
     * Designer Code
    this.eventOffsetTimer.Interval = 500;
    this.eventOffsetTimer.Tick += new System.EventHandler(this.eventOffsetTimer_Tick);
    */
    eventOffsetTimer.Stop();
    eventOffsetTimer.Start();
}

private void eventOffsetTimer_Tick(object sender, EventArgs e)
{
    eventOffsetTimer.Stop();
    //Time consuming stuff...
    MessageBox.Show(numericUpDown1.Value.ToString());
}

我想知道在触发事件前几秒钟完成偏移的最佳做法是什么。是否有微软鼓励使用的内置方式?启动和停止 Timer 是一件简单的事情,但似乎有微软鼓励的方法。

【问题讨论】:

  • 在使用.Stop()重置计时器后,您应该使用.Restart()
  • 我不知道 System.Windows.Forms.Timer.Restart()。 Microsoft 文档中似乎没有 Restart 方法。你指的是哪个定时器?
  • 我的错:我通常使用System.Timer,它有一个.Restart(),因为.Start() 只继续当前运行。我不知道任何内置解决方案。我认为你必须建立自己的。这可能很有趣:stackoverflow.com/questions/648700/…
  • 这些天的最佳实践是异步/等待并取消然后重新创建延迟任务。

标签: c# .net winforms


【解决方案1】:

您应该使用.Restart()。它首先释放 Timer,然后再次启动它。

提示:您不需要将.Stop().Restart() 一起使用

【讨论】:

  • 我不知道 System.Windows.Forms.Timer.Restart()。 Microsoft 文档中似乎没有 Restart 方法。你指的是哪个定时器?
  • 你可以使用System.Timers.Timer
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-04-07
  • 2013-10-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-19
相关资源
最近更新 更多